Insertion sort using java

What is insertion sort in data structure?
Insertion Sort Algorithm. Insertion sort is the sorting mechanism where the sorted array is built having one item at a time. The array elements are compared with each other sequentially and then arranged simultaneously in some particular order.

  Algorithm

  Now we have a bigger picture of how this sorting technique works, so we can derive simple    steps by which we can achieve insertion sort.

Step 1 − If it is the first element, it is already sorted. return 1;
Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the 
         value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted
   Let's see a simple java program to sort an array using insertion sort algorithm.

   import java.util.*;
   public class Insertionsort{
public static void inserttion(int[] arr){
int k=0, j=0;
        for(int i=1; i<arr.length; i++){
        k = arr[i];
        for(j = i-1; j>=0 && k<arr[j]; j--)
           arr[j+1] = arr[j];
        arr[j+1] = k;
        }
}
public static void print(int[] arr){
int i=0;
while(i<arr.length)
{
System.out.print(arr[i]+" ");
i++;
}
}
public static void main(String[] args)throws Exception{
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
int arr[] = new int[size];
for(int i=0; i<arr.length; i++){
arr[i]=sc.nextInt();
}
inserttion(arr);
print(arr);
}
}


Comments

Popular posts from this blog

Caesar Cipher Algo

Huffman coding algoritnm

PlayFairCipher algorytham