Insertion Sort in Java Using While Loop

Insertion sort in java program. 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.

Insertion Sort in Java Program

Insertion sort is a straightforward sorting technique that allows for in-place sorting of an array one element at a time. In-place sorting refers to the modification of the original array without the use of temporary structures. Insertion sort is a sorting mechanism that builds a sorted array one item at a time. The array members are compared progressively before being placed in a specific order.

While Loop in Java

The while loop in Java is a control flow statement that allows code to be repeated based on a Boolean condition. The while loop is similar to a looping if statement. If the condition evaluates to true, the body of the loop will be executed, and we will proceed to the update expression.

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