Search code examples
javasortinginsertion-sort

Simple Insertion Sort in Java


I had written a simple insertion sort program but the output is not coming correctly.

class InsertionSort{
    public static void main(String h[]){
    int[] a = {5,4,3,2,1};
    int i,j,temp;
        for(i=1;i<a.length;i++){
            j = i-1; 
            while(i>0 && a[j] > a[i]){
                temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
        for(int x=0; x<a.length;x++){
            System.out.println(a[x]);   
        }
    }
}

Solution

  • /*this program sort in ascending order by insertion sort */  
    class InsertionSort{
    public static void main(String h[]){
    int[] a = {100,12,31, 5, 4, 3, 2, 1 };
    int i, j, temp;
        for (i = 1; i < a.length; i++)
        {
            j = i - 1;
            while (j >= 0 && a[j] > a[i] )
            {
                temp = a[i];
                a[i] = a[j];
                a[j] = temp;
                i=j;
                j--;
    
            }
        }
    for(int x=0; x<a.length;x++){
        System.out.println(a[x]);   
      }
    }
    }
    /*this program sort in descending order by insertion sort */  
    class InsertionSort{
    public static void main(String h[]){
    int[] a = {100,12,31, 5, 4, 3, 2, 1 };
    int i, j, temp;
        for (i = 1; i < a.length; i++)
        {
            j = i - 1;
            while (j >= 0 && a[j] < a[i] )
            {
                temp = a[i];
                a[i] = a[j];
                a[j] = temp;
                i=j;
                j--;
    
            }
        }
    for(int x=0; x<a.length;x++){
        System.out.println(a[x]);   
      }
    }
    }