Guest User

Untitled

a guest
Jan 15th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. class InsertionSort {
  2. /*Function to sort array using insertion sort*/
  3. void sort(int arr[]) {
  4. int n = arr.length;
  5. for (int i = 1; i < n; ++i) {
  6. int key = arr[i];
  7. int j = i - 1;
  8.  
  9. /* Move elements of arr[0..i-1], that are
  10. greater than key, to one position ahead
  11. of their current position */
  12. while (j >= 0 && arr[j] > key) {
  13. arr[j + 1] = arr[j];
  14. j = j - 1;
  15. }
  16. arr[j + 1] = key;
  17. }
  18. }
  19.  
  20. /* A utility function to print array of size n*/
  21. static void printArray(int arr[]) {
  22. int n = arr.length;
  23. for (int i = 0; i < n; ++i)
  24. System.out.print(arr[i] + " ");
  25.  
  26. System.out.println();
  27. }
  28.  
  29. // Driver method
  30. public static void main(String args[]) {
  31. int arr[] = {12, 11, 13, 5, 6};
  32.  
  33. InsertionSort ob = new InsertionSort();
  34. ob.sort(arr);
  35.  
  36. printArray(arr);
  37. }
  38. }
Add Comment
Please, Sign In to add comment