How to code Insertion sort in java

    0
    21
    Spread the love
    • 1
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
      1
      Share


    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]);
    }
    }
    }

    Don't miss out!
    Subscribe To Newsletter

    Receive top technical news, lesson ideas, travel tips and more!

    Invalid email address
    Give it a try. You can unsubscribe at any time.

    Spread the love
    • 1
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
      1
      Share

    LEAVE A REPLY

    Please enter your comment!
    Please enter your name here