Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. // Java program for implementation of Insertion Sort
  2. class InsertionSort
  3. {
  4. /*Function to sort array using insertion sort*/
  5. void sort(int arr[])
  6. {
  7. int n = arr.length;
  8. for (int i=1; i<n; ++i)
  9. {
  10. int key = arr[i];
  11. // now that we need to insert new element, we will have to shift element from sorted part
  12. // i always points to the unsorted part. So go to sorted part we set j = i-1
  13. int j = i-1;
  14.  
  15. /* Move elements of arr[0..i-1], that are
  16. greater than key, to one position ahead
  17. of their current position */
  18. while (j>=0 && arr[j] > key)
  19. {
  20. arr[j+1] = arr[j];
  21. j = j-1;
  22. }
  23. arr[j+1] = key;
  24. }
  25. }
  26.  
  27. /* A utility function to print array of size n*/
  28. static void printArray(int arr[])
  29. {
  30. int n = arr.length;
  31. for (int i=0; i<n; ++i)
  32. System.out.print(arr[i] + " ");
  33.  
  34. System.out.println();
  35. }
  36.  
  37. // Driver method
  38. public static void main(String args[])
  39. {
  40. int arr[] = {12, 11, 13, 5, 6};
  41.  
  42. InsertionSort ob = new InsertionSort();
  43. ob.sort(arr);
  44.  
  45. printArray(arr);
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement