Advertisement
LoganBlackisle

InsertionSort

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