Showing posts with label Insertion sort. Show all posts
Showing posts with label Insertion sort. Show all posts

Insertion sort in Java

As like earlier tutorial Bubble sort, in this tutorial we will see about Insertion sort in Java with simple example. Unlike the other sorting algorithm insertion sort passes through the array only once.
Basically insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. 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. Below sample image will explain about how Insertion sort algorithm works.
Insertion sort example in Java
Now lets see simple insertion sort in java.


public class InsertionSort {

 public static void main(String[] args) {

  int values[] = { 5, 4, 8, 6, 9, 1, 7, 3, 2 };

  System.out.print("\nBefore sort : ");
  printArray(values);

  insertionSort(values);

  System.out.print("\nAfter sort : ");
  printArray(values);
 }

 private static void insertionSort(int[] array) {
  int i;
  for (int j = 1; j < array.length; j++) {
   int key = array[j];
   for (i = j - 1; (i >= 0) && (array[i] > key); i--) {
    array[i + 1] = array[i];
   }
   array[i + 1] = key;
  }
 }

 private static void printArray(int[] array) {
  for (int i = 0; i < array.length; i++) {
   System.out.print(array[i] + ", ");
  }
 }
}

OUTPUT:

Before sort : 5, 4, 8, 6, 9, 1, 7, 3, 2, 
After sort : 1, 2, 3, 4, 5, 6, 7, 8, 9,