Insertion Sort Algorithm Implementation in Java

[1507 views]

What is Insertion Sort?

Insertion sort is the simplest sorting algorithm in which the elements are transferred to the right position one at a time. An insertion sort has many benefits because of simplicity and low overhead.

In an Insertion sort, the first element in the array is considered as sorted. In an insertion sort, each element in the array is checked with the previous elements, which results in a growing sorted output array. With every iteration, the insertion sorting algorithm removes one element at a time and finds it's appropriate location within the sorted array and inserts it there in the sorted list. The iteration continues until the whole list is sorted.

For Insertion Algorithm, you can refer our previous post Algorithm for Insertion Sort

Insertion Sort Algorithm in Java

public class insertionsort { int a[]={25,20,30,77,97,87,81,93,100,5,68}; //array a has sample data to sort public void display(){ //display content of array for(int i=0;i<a.length;i++){ System.out.print(a[i]+" "); } System.out.println(" "); } public void sortArray(){ //sort array using insertion sort algorithm int in,out; for(out=1;out<=a.length-1;out++){ //it begins with 1st index int temp = a[out]; in=out; while(in>0 && a[in-1]>=temp){ //if condition is satisfied then swap a[in]=a[in-1]; a[in-1]=temp; in--; } } } public static void main (String[] args){ insertionsort i = new insertionsort(); System.out.print("Array before sort: "); i.display(); i.sortArray(); System.out.print("Array after insertion sort: "); i.display(); } }

Output:

C:\Users\SK\Desktop>javac insertionsort.java C:\Users\SK\Desktop>java insertionsort Array before sort: 25 20 30 77 97 87 81 93 100 5 68 Array after insertion sort: 5 20 25 30 68 77 81 87 93 97 100

Algorithm Logic Test

Our Quiz prepared by Experts Helps you identify your knowledge in Algorithms. Everyone should atleast attempt this Quiz Once.