Cahyadi_SN

Insertion Sort Program

Mar 30th, 2021 (edited)
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.03 KB | None | 0 0
  1. /**
  2.  * InsertionSort Program
  3.  * Program to implement InsertionSort
  4.  *
  5.  * @author Cahyadi Surya Nugraha
  6.  * @version 1.0
  7.  * @since March 31th 2021
  8.  */
  9.  
  10. public class InsertionSortApp
  11. {
  12.     static void insertionSort(int[] arr)
  13.     {
  14.         int size_arr = arr.length;
  15.         for (int i = 1; i < size_arr; i++)
  16.         {
  17.             int key = arr[i];
  18.             int j = i-1;
  19.             for (; j > -1 && arr[j] > key; j--)
  20.                 arr[j+1] = arr[j];
  21.  
  22.             arr[j+1] = key;
  23.         }
  24.     }
  25.  
  26.     static void printArray(int[] arr)
  27.     {
  28.         for (int value : arr)
  29.         {
  30.             System.out.print(value + " ");
  31.         }
  32.     }
  33.  
  34.     public static void main(String[] args)
  35.     {
  36.         int test_array[] = {54,122,5,4,2,3,45,12,52};
  37.  
  38.         System.out.println("List dalam array sebelum di InsertionSort:");
  39.         printArray(test_array);
  40.  
  41.         insertionSort(test_array);
  42.  
  43.         System.out.println("\n\nList dalam array setelah di InsertionSort:");
  44.         printArray(test_array);
  45.     }
  46. }
  47.  
Add Comment
Please, Sign In to add comment