Insertion Sort Algorithm in Java Programming

Insertion Sort Algorithm

Insertion Sort Algorithm example in Java programming :




public class InsertionSortExample {
  
  static int step = 1;
   
    public static void main(String[] args) {
          
        int[] input = { 7, 21, 91, 43, 23, 17, 34, 9, 1 };
        insertionSort(input);
    }
      
    private static void printNumbers(int[] input) {
          
      System.out.println("Step "+step);
      System.out.println("-----------------------------");
      step++;
       
        for (int i = 0; i < input.length; i++) {
           
            System.out.print(input[i] + ", ");
             
        }
         
        System.out.println("\n");
    }
  
    public static void insertionSort(int array[]) {
       
        int n = array.length;
         
        for (int j = 1; j < n; j++) {
           
            int key = array[j];
            int i = j-1;
             
            while ( (i > -1) && ( array [i] > key ) ) {
               
                array [i+1] = array [i];
                i--;
                 
            }
             
            array[i+1] = key;
            printNumbers(array);
        }
    }
}


OUTPUT
Step 1
-----------------------------
7, 21, 91, 43, 23, 17, 34, 9, 1,
Step 2
-----------------------------
7, 21, 91, 43, 23, 17, 34, 9, 1,
Step 3
-----------------------------
7, 21, 43, 91, 23, 17, 34, 9, 1,
Step 4
-----------------------------
7, 21, 23, 43, 91, 17, 34, 9, 1,
Step 5
-----------------------------
7, 17, 21, 23, 43, 91, 34, 9, 1,
Step 6
-----------------------------
7, 17, 21, 23, 34, 43, 91, 9, 1,
Step 7
-----------------------------
7, 9, 17, 21, 23, 34, 43, 91, 1,
Step 8
-----------------------------
1, 7, 9, 17, 21, 23, 34, 43, 91,

Post a Comment

0 Comments