Insertion Sort


  • Time Complexity - O(n^2) || Space Complexity - O(1)
  • We maintain array like this - [sorted portion | unsorted portion] (same as selection sort)
  • Now in every iteration of i , we take first element of unsorted portion and try to insert it in sorted portion at it's correct place by comparing the currently picked first element of unsorted  and swapping it repeteadly with previous elements in sorted portion [starting from last element of sorted portion] and swapping them according to our need whether we want to sort in increasing or decreasing order.
  • While doing the above swapping, remember we are moving from last to first element of sorted portion and swapping them. If sorting in increasing order, if we find any element before swapping to be less than the current element, we do not swap and break from the inner loop of j and continue our next iteration of i loop.
  • Insertion sort is best sorting algorithm if we are continuously getting new inputs and we have to place the new input to it's right place.


public class Main {
    public static void main(String[] args) throws Exception {
        int[] arr={1,4,4,5,6,2,3,90,120,43,0};
        // int[] arr = {20,1};
        
        System.out.println("UnSorted Array :");
        for(int i=0;i<arr.length;i++){
            System.out.print(arr[i]+" ");
        }
        System.out.println();
        // Insertion sort
        
        // [sorted array | unsorted array] - we will maintain array like this
        // i loop is to iterate for each element. i loop will maintain an undoretd array
        for(int i=0;i<arr.length;i++){
           // j loop will maintain a sorted array and it is used to insert the first element of i loop at it's correct position in sorted array by comparing with each element in sorted array and swapping
           for(int j=i;j>0;j--){
               if(arr[j-1]>arr[j]){
                   int temp = arr[j-1];
                   arr[j-1]=arr[j];
                   arr[j]=temp;
               }
               // if we get any element less than current element, then it is already sorted for that iteration of i, hence we will break and go to next iteration of i
               else{
                   break;
               }
           }
           
        }        
        
        System.out.println();
        System.out.println("Sorted Array in increasing order:");
        for(int i=0;i<arr.length;i++){
            System.out.print(arr[i]+" ");
        }
    }
}


Output: 

UnSorted Array :
1 4 4 5 6 2 3 90 120 43 0 

Sorted Array in increasing order:
0 1 2 3 4 4 5 6 43 90 120 

Comments

Popular posts from this blog

Binary Heap - Introduction

Divide and Conquer - Introduction

Bubble Sort