Insertion sort program in java using while loop

Insertion sort program in java using while loop. There is an insertion sort program in the Java programming language. The value will be added any time the element is iterated in the program. For Java beginners, this program is a Java middle level sorting program. Insertion sort is a simple sorting method that produces a sorted array one item at a time.

public class Main
{ 
public static void sort(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; 
} 
} 
public static void main(String a[])
{ 
int[] arr1 = {45,67,34,23,68,87,64}; 
System.out.println("Before sort"); 
for(int i:arr1){ 
System.out.print(i+" "); 
} 
System.out.println(); 
sort(arr1);
System.out.println("After sort"); 
for(int i:arr1){ 
System.out.print(i+" "); 
} 
} 
} 

 

Output:

Before sort

45 67 34 23 68 87 64

After sort

23 34 45 64 67 68 87