7/22/11

Insertion sort with program code and tutorial

Insertion sort is divided into two parts:
     1. Straight Insertion Sort
     2. Shell Sort 

Insertion sort is a simple sort algorithm, a comparison sort in which the sorted array [or list] is built one entry at a time. It is much less efficient on large lists than the more advanced  Algorithms such as Quick sort, Merge sort or Heap sort.


In abstract terms , in each iteration the sort  removes an element from the input data , inserting at the correct position in an array of  already sorted list, until no elements are left in the input.

Program Code :

public class Insertion {

    public void InSort(int a[],int n){
        int key=0;
        int j=0;
        for (int i=1;i<n;i++){
            key=a[i];
            j=i-1;
            while((j>=0) && (a[j]>key)){
                a[j+1]=a[j];
                j=j-1;
            }
            a[j+1]=key;
        }
        
        for(int i=0;i<n;i++){
            System.out.println(a[i]);    
        }
    }
    
    public static void main(String[] args) {
        new Insertion().InSort(new int[] {66,45,76,12,9,4},6);// Elements and number of elements
    }
}

SHARE THIS POST:

Related Posts:

  • Minimax Algorithm Tutorial There are plenty of application in AI but games are the most important thing in today's world and nowadays every OS comes with two player games like chess, checkers etc. So there are algorithm that help to design these ga… Read More
  • Counting Sort Algorithm with Example After a long interval of time I am writing a post on ALGORITHMS. After writing posts on Heap Sort, Merge Sort and Insertion Sort, I decided to write on Counting Sort. Counting sort is an algorithm for sorting a collection … Read More
  • HeapSort ( array Based) implementation in Java There are two types of heaps. First one is Max heap and second one is Min heap. Heap (Max/Min) is a special type of binary tree.The roots of  the max heap is greater than its child roots. Other heap is Min heap it is al… Read More
  • Algorithm Tutorials - Part 1 : Ad-Hoc Problems I will start with the very basic of Algorithms. Before moving on to the different algorithms, let's first see what does an algorithm actually mean? Definition :  A process or set of rules to be followed i… Read More
  • Binary Search Tree (BST) Algorithm Tutorial Earlier we had a tutorial on Binary Seach Tree Basics, which you can check for refreshing the knowledge about it. Today we will be taking a look on BST algorithm and implementing it using Java. Binary Search Tree is no… Read More