Insertion Sort in Java is an algorithm that is used to sort integer values. It can be implemented very easily and is efficient for small data sets. However, Insertion Sort in Java is less efficient when it comes to larger data sets.
In insertion sorting, algorithm divides the elements in two parts, one which is sorted and its size keeps increasing, the other is unsorted and its size keeps decreasing.
How does Insertion Sort works in Java?
Assume that you have 5 unsorted numbers and you want to sort it in ascending way. What you will do is place smallest number at first and then sort it in an increasing manner. Similarly, Insertion Sort Java compare the first value with the next value, if it is small it is placed ahead of it, if not it remains in same position.
Features of Insertion Sort in Java:
Example of Insertion Sort in Java:
public class InsertionSort { public static void main(String[] args) { int i; int array[] = { 12, 9, 4, 55, 111, 1, 3, 10,2,11 }; System.out.println("Befor value the sort:"); for (i = 0; i < array.length; i++) System.out.print(array[i] + " "); System.out.println(); insertion_Sort(array, array.length); System.out.print("After Values the sort:\n"); for (i = 0; i < array.length; i++) System.out.print(array[i] + " "); System.out.println(); } private static void insertion_Sort(int[] array, int a) { for ( int x = 1; x < a; x++) { int y=x; int A=array[x]; while ((y > 0) && (array[y1] > A)){ array[y] = array[y1]; y; } array[y] = A; } } }
Output:
Unsorted value:
12 9 4 55 111 1 3 10 2 11
Sorted Value:
1 2 3 4 9 10 11 12 55 111
If you enjoyed this post then why not add us on Google+? Add us to your Circles
Liked it! Share this Tutorial

Discuss: Insertion Sort Java
Post your Comment