Pages

15 June 2012

Quick Sort using Java

Here's another program form DSF .This time its the sorting techniques.Let's Start of with Quick Sort.Bet you won't find an easier program than the one's here on Tech Junkieee...
Working of quick sort algorithm:
Input:
12 9 4 99 120 1 3 10 13




Output:
1 3 4 10 12 13 99 120



Program For Quick Sort Using Java
/**
 *
 * @author The Cyber Soul
 */
import java.io.*;
public class QuickSort {
    public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("***QUICK SORT***");
int i,n;
System.out.println("How many elements do you want to sort");
n=Integer.parseInt(br.readLine());
int array[]=new int[n];
System.out.println("Enter the values to be sorted");
for(i=0;i<n;i++)
{
    array[i]=Integer.parseInt(br.readLine());
}
System.out.println("Values before the Sort:\n");
for(i=0;i<array.length;i++)
{
    System.out.print(array[i]+" ");
}
System.out.println();
QuickSort s=new QuickSort();
s.quick_srt(array,0,n-1);
System.out.println("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 QUICK SORT***");
}
    public  void quick_srt(int a[],int left,int right)
    {
        int index=partition(a,left,right);
        if(left<index-1)
        {
            quick_srt(a,left,index-1);
        }
        if(index<right)
        {
            quick_srt(a,index,right);
        }
    }

     int partition(int a[],int left,int right)
    {
  int i=left,j=right;
  int tmp;
  int pivot=a[(left+right)/2];
  while(i<=j)
  {
      while(a[i]<pivot)
          i++;
      while(a[j]>pivot)
          j--;
      if(i<=j)
      {
          tmp=a[i];
          a[i]=a[j];
          a[j]=tmp;
          i++;
          j--;
      }
  }

  return i;
     }
    
}



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