Ad Home

Theme images by kelvinjay. Powered by Blogger.

Travel

Header Ads

Java

Selenium

UFT

Framework

General QA Concept

BDD

» » 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.


code


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] ;
j=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 ))
{
anArray[j]=anArray[j-1];
//change the position if the element.
anArray[j-1]=temp;
//This condition is for checking the negative element of the array not required i all your element is positive
j--;
}
}


for(int i=0;i<len;i++)
{
System.out.println(anArray[i]);
}
}
}

«
Next
Newer Post
»
Previous
Older Post

No comments:

Leave a Reply