Java program to implement insertion sort


This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorted. For example, the lower part of an array is maintained to be sorted. An element which is to be inserted in this sorted sub-list has to find its appropriate place and then it has to be inserted there. Hence the name, insertion sort.

The array is searched sequentially and unsorted items are moved and inserted into the sorted sub-list (in the same array).

Algorithm

1.If it is the first element, it is already sorted. return 1;
2.Pick next element
3.Compare with all elements in the sorted sub-list
4.Shift all the elements in the sorted sub-list that is greater than the value to be sorted
5.Insert the value
6.Repeat until the list is sorted

Example

Live Demo

public class InsertionSort {
   public static void main(String args[]){
      int array[] = {10, 20, 25, 63, 96, 57};
      int size = array.length;

      for (int i=1 ;i< size; i++){
         int val = array[i];
         int pos = i;

         while(array[pos-1]>val &amp;&amp; pos>0){
            array[pos] = array[pos-1];
            pos = pos-1;
         }
         array[pos] = val;
      }

      for (int i=0 ;i< size; i++){
         System.out.print(" "+array[i]);
      }
   }
}

Output

10 20 25 57 63 96

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 13-Mar-2020

631 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements