Insertion Sort Algorithm

It is the kind of sorting algorithm that works by iterating over an array and inserting each element at its correct position in the sorted part of the array.

Space Complexity – O(1)

Best Case Time Complexity – O(N). This case will occur if the array is already sorted where the outer loop runs from 0 to n and the inner loop runs 0 times.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import java.util.*;
public class Main {
public static void main(String[] args) {
int arr[]= {5,4,10,1,6,2};
insertionSort(arr);
for(int i:arr){
System.out.println(i);
}
}
public static void insertionSort(int arr[]){
for(int i=0;i<arr.length;i++){
int j=i;
while(j>0 && arr[j-1]>arr[j]){
int temp=arr[j-1];
arr[j-1]=arr[j];
arr[j]=temp;
j--;
}
}
}
}
import java.util.*; public class Main { public static void main(String[] args) { int arr[]= {5,4,10,1,6,2}; insertionSort(arr); for(int i:arr){ System.out.println(i); } } public static void insertionSort(int arr[]){ for(int i=0;i<arr.length;i++){ int j=i; while(j>0 && arr[j-1]>arr[j]){ int temp=arr[j-1]; arr[j-1]=arr[j]; arr[j]=temp; j--; } } } }
import  java.util.*;
public class Main {
    public static void main(String[] args) {
        int arr[]= {5,4,10,1,6,2};
        insertionSort(arr);
        for(int i:arr){
            System.out.println(i);
        }
    }
   public static  void insertionSort(int arr[]){
        for(int i=0;i<arr.length;i++){
            int j=i;
            while(j>0 && arr[j-1]>arr[j]){
                int temp=arr[j-1];
                arr[j-1]=arr[j];
                arr[j]=temp;
                j--;
            }
      }
   }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

WhatsApp Icon Join For Job Alerts