Java insertion sort algorithm example

Insertion sort

Insertion sort is a simple sorting algorithm that builds the final sorted array or list one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.

It iterates, take one input element each repetition, and growing a sorted output list. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain.

Example

package com.w3spoint;
 
public class Test {
     public static int[] insertionSort(int data[]) {
	int temp;
        for (int i = 1; i < data.length; i++) { 
            for(int j = i ; j > 0 ; j--){
                if(data[j] < data[j-1]){
                    temp = data[j];
                    data[j] = data[j-1];
                    data[j-1] = temp;
                }
            }
        }
       return data;
     }
 
     private static void printNumbers(int[] data) {          
        for (int i = 0; i < data.length; i++) {
            System.out.print(data[i]);
            if(i != data.length-1){
            	System.out.print(", ");
            }
        }
        System.out.println("\n");
     }
 
	public static void main(String args[]){
		int[] data = {8, 2, 4, 9, 3, 6}; 
		//Print array elements
		printNumbers(data);
		int[] sortedDate = insertionSort(data);  
		//Print sorted array elements
		printNumbers(sortedDate);
	}
}

Output

8, 2, 4, 9, 3, 6
 
2, 3, 4, 6, 8, 9
Please follow and like us:
Content Protection by DMCA.com