Insertion Sort in Java

EMBED

Saved by @Barha #java

Step 0: Insertion sort

 public void sort(int array[]) { 
     for (int i = 1; i < array.length; i++) { 
          int key = array[i]; 
          int j = i - 1; 
          while (j >= 0 && array[j] > key) { 
              array[j + 1] = array[j]; 
              j = j - 1; 
          } 
          array[j + 1] = key; 
      } 
 }
content_copyCOPY

Step 1: Prints the array

void printArray(int array[]) { 
     for (int i = 0; i < array.length; i++){ 
        System.out.print(array[i] + " "); 
     }
     System.out.println(); 
 } 
content_copyCOPY

Here is a java method to sort an array using the Insertion sort.

,