CodesJava

Easy learning with example program codes

Java insertion sort algorithm example


Sorting algorithm

A sorting algorithm is a way to put elements of a list in a certain order. The most-used orders are numerical order and lexicographical order. Efficient sorting is important for optimizing the use of other algorithms (like search and merge algorithms) which require input data to be in sorted lists. It is also often useful for canonicalizing data and for producing human-readable output.

The output must satisfy following two conditions:

  • The output is in no decreasing order i.e.each element is no smaller than the previous element according to the desired total order.
  • The output is a reordering of elements but with all of the original elements of the input.

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.codesjava;
 
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


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap