Pages

15 June 2012

Insertion Sort Using Java

This is the last kind of sort you would need for DSF and that's insertion sort.Lets consider an example of it.

Here's the program for it .


Program for Insertion Sort Using Java

/**
 *
 * @author The Cyber Soul
 */import java.io.*;
public class InsertionSort {
    public static void main(String a[]) throws IOException{
 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("***INSERTION SORT***");
  int i,n;
  System.out.println("Enter the length of Array");
  n=Integer.parseInt(br.readLine());
  int array[] = new int[n];
  System.out.println("Enter the values");
  for(i=0;i<n;i++)
  {
      array[i]=Integer.parseInt(br.readLine());
  }
  System.out.println(" Selection Sort\n\n");
  System.out.println("Values Before the sort:\n"); 
  for(i = 0; i < array.length; i++)
  System.out.print( array[i]+"  ");
  System.out.println();
  insertion_srt(array, array.length); 
  System.out.print("Values after the sort:\n"); 
  for(i = 0; i <array.length; i++)
  System.out.print(array[i]+"  ");
  System.out.println();
  System.out.println("***END OF INSERTION SORT***");
  }

  public static void insertion_srt(int array[], int n){
  for (int i = 1; i < n; i++){
  int j = i;
  int B = array[i];
  while ((j > 0) && (array[j-1] > B)){
  array[j] = array[j-1];
  j--;
  }
  array[j] = B;
  }
  }

}

Technorati Delicious Reddit BlinkList Furl Mixx Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

0 comments:

Post a Comment

Please Feel free to Share your view with us ....

Related Posts Plugin for WordPress, Blogger...
Search Engine Submission - AddMe Hypersmash.com Blogarama - The Blog Directory Bloggers - Meet Millions of Bloggers