package com.sbs.sort;

/**

* @author Bhargava

*

* Time Complexity of Insertion Sort is O(n power 2) Worst Case O(n) best case

* Recommended for Smallest array of elements.

* If you observe Array.sort() method in java.util api, if the array length is smaller than 7 our api is following * insertion sort.

*/

public class InsertionSort {

/**

* @param args

*/

public static void main(String[] args) {

long intialTime = System.currentTimeMillis();

int[] array = { 24, 13, 9, 64, 7, 23, 34, 47 };

System.out.print(" Befor Sorting [ ");

for (int j = 0; j < array.length; j++) {

System.out.print(array[j] + " ");

}

for (int i = 1; i < array.length; i++) {

int j = i - 1;

int temp = 0;

while (j >= 0) {

if (array[j + 1] < array[j]) {

temp = array[j];

array[j] = array[j + 1];

array[j + 1] = temp;

}

j--;

}

}

System.out.print(" After Sorting [ ");

for (int j = 0; j < array.length; j++) {

System.out.print(array[j] + " ");

}

System.out.print("]");

System.out.println(" Time Lapse :"

+ (System.currentTimeMillis() - intialTime) + " ms ");

}

}

/**

* @author Bhargava

*

* Time Complexity of Insertion Sort is O(n power 2) Worst Case O(n) best case

* Recommended for Smallest array of elements.

* If you observe Array.sort() method in java.util api, if the array length is smaller than 7 our api is following * insertion sort.

*/

public class InsertionSort {

/**

* @param args

*/

public static void main(String[] args) {

long intialTime = System.currentTimeMillis();

int[] array = { 24, 13, 9, 64, 7, 23, 34, 47 };

System.out.print(" Befor Sorting [ ");

for (int j = 0; j < array.length; j++) {

System.out.print(array[j] + " ");

}

for (int i = 1; i < array.length; i++) {

int j = i - 1;

int temp = 0;

while (j >= 0) {

if (array[j + 1] < array[j]) {

temp = array[j];

array[j] = array[j + 1];

array[j + 1] = temp;

}

j--;

}

}

System.out.print(" After Sorting [ ");

for (int j = 0; j < array.length; j++) {

System.out.print(array[j] + " ");

}

System.out.print("]");

System.out.println(" Time Lapse :"

+ (System.currentTimeMillis() - intialTime) + " ms ");

}

}