Advertisement
Samuel_Berkat_Hulu

Insertion Sort

Apr 6th, 2021
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.00 KB | None | 0 0
  1.  
  2. /**
  3.  * Write a description of class Insertion_Sort here.
  4.  *
  5.  * @Samuel Berkat Hulu
  6.  * @version 5.0
  7.  */
  8. public class Insertion_Sort
  9. {
  10.     public static void insertionSort(int arr[]) {
  11.         for (int j = 1; j < arr.length; j++) {
  12.             int key = arr[j]; int i = j-1;
  13.                 while ( (i > -1) && ( arr[i] > key ) ) {
  14.                     arr[i+1] = arr[i]; i--;
  15.                     }
  16.                         arr[i+1] = key;
  17.                 }
  18. }
  19.     static void printArray(int arr[]) {
  20.         int len = arr.length;
  21.             for (int i= 0; i<len; i++)
  22.                 System.out.print(arr[i] + " " );
  23.                     System.out.println();
  24. }
  25.     public static void main(String args[]){
  26.         int[] arr1 = {21,18,15,23,52,12,61};
  27.             System.out.println("Array sebelum penyisipan:");
  28.                 printArray(arr1);
  29.                   insertionSort(arr1);
  30.             System.out.println("Array array setelah penyisipan:");
  31.                 printArray(arr1);
  32. }
  33. }
  34.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement