afiqakraam

insertionsort

Apr 2nd, 2021 (edited)
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.67 KB | None | 0 0
  1. public class InsertionSort {
  2. public static void insertionSort(int arr[]) { for (int j = 1; j < arr.length; j++) { int key = arr[j]; int i = j-1;
  3. while ( (i > -1) && ( arr[i] > key ) ) { arr[i+1] = arr[i]; i--; }
  4. arr[i+1] = key;
  5. }
  6. }
  7. static void printArray(int arr[]) { int len = arr.length;
  8. //simple for loop to print the elements of sorted array for (int i= 0; i<len; i++)
  9. System.out.print(arr[i] + " " );
  10. System.out.println();
  11. }
  12. public static void main(String args[]){ int[] arr1 = {21,18,15,23,52,12,61};
  13. //calling the sort function which performs insertion sort insertionSort(arr1);
  14. //calling the printArray function which performs printing of array printArray(arr1);
  15. }
  16. }
Add Comment
Please, Sign In to add comment