Header Ads

How to code Insertion sort in java

Please checkout Sorting Algorithm Animations  before I start my coding. This is also a great site to refer http://www.algolist.net/Algorithms/Sorting/Insertion_sort

Please refer this two sites before starting your coding.


public class InsertionSort  {

public static void main(String[] args)
int[] anArray={5,2,4,10,6};
//this is array of numbers on which i will do my sort
int len=anArray.length;
//find out the length of the array
int temp,j;

for (int i=0;i<len;i++)
//temporary storing the next element of the array
temp=anArray[i] ;
//cheeking if the next element of the array is greater than the previous element of the array
while((j>0) && (anArray[j-1]>temp ))
//change the position if the element.
//This condition is for checking the negative element of the array not required i all your element is positive

for(int i=0;i<len;i++)

Powered by Blogger.