Insertion Sort In Java

Sharing is healthy !!

Hi, everyone you are here to learn insertion sort in java with an example.

Insertion Sort

Insertion sort is a sorting algorithm that forms final sorted array ( one each at a time).

It is one of the simplest sorting algorithm compared to advanced sorting algorithms, namely heapsort and quicksort.

Insertion sort is useful for small sets. Also it is not a fast algorithm, because it uses nested loop to shift items into place.

Let’s see code implementation,

INSERTION SORT IN JAVA EXAMPLE:

Also Read – Bubble Sort Java Program

import java.util.Scanner;

public class Insertion_Sort {

public static void sort_insertion(int arr[]){

int a = arr.length;
int x;
int y;
int temp;

for(x = 1;x < a;x++){
y = x;
temp = arr[x];

while(y > 0 && temp < arr[y - 1]){
arr[y] = arr[y - 1];
y = y - 1;
}
arr[y] = temp;
}
}

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
System.out.println("Insertion Sort in Java");
int b;
int c;

System.out.println("Please enter number of integer elements: ");
b = sc.nextInt();
int arr[] = new int[b];
System.out.println("Please enter " + b + " integer elements");

for(c = 0;c < b;c++)
arr[c] = sc.nextInt();

sort_insertion(arr);

System.out.println("Integer elements after sorting");

for(c = 0;c < b;c++)
System.out.print(arr[c] + " ");
System.out.println();

}
}

Output:

Insertion Sort In Java

As you can see in the above example in every iteration insertion sort separates an element from input and inserts it into the correct position until all elements are sorted.

In the above example the selection of which element to remove from input is random.

Sharing is healthy !!

Leave a Reply

Your email address will not be published.