Showing posts with label Quick Sort. Show all posts
Showing posts with label Quick Sort. Show all posts

Sunday, 19 October 2014

Quick Sort in Java

Structure of the Problem Requirements 

In this Program we will learn about Quick Sorting Algorithm. Quick Sort is a very efficient sorting algorithm. In this algorithm we divided our problem into two Parts. One of the Part is the partition of the phases and other is sorting the Phases.In first phase we divide our problems in further two array and in both arrays Sorting is done in first phase, then in second phase both array combines again and then sort them and resultant array display in sorting order

SOURCE CODE



import java.io.*;
import java.util.*;
public class QuickSort
{
public static voidmain(String args[]) throws IOException
{
InputStreamReaderisr=new InputStreamReader(System.in);
  BufferedReader br=new BufferedReader(isr);
  int x[]=new int[40];
  int size,i;
  char st[]=newchar[40];
  Operate op=new Operate();
 System.out.print("Enter no.of characters:");
 size=Integer.parseInt(br.readLine());


  System.out.println("\nEnter "+size+" characters :");

 for (i=0;i<size;i++)
 {
 Scanner reader = new Scanner(System.in);
char c = reader.next().charAt(0);
 st[i]=c;
x[i]=(int)st[i];

}

op.quicksort(x,0,size-1,size);
System.out.println("Sorted elements: ");
  for(i=0;i<size;i++)
  {
  char c=(char)x[i];
    System.out.println(" "+c+"\n");
 }

}
}
class Operate
{
void quicksort(int x[],int first,int last,int size){
    int pivot,j,temp,i;

     if(first<last){
         pivot=first;
         i=first;
         j=last;

         while(i<j){
             while(x[i]<=x[pivot]&&i<last)
                 i++;
             while(x[j]>x[pivot])
                 j--;
             if(i<j){
                 temp=x[i];
                  x[i]=x[j];
                  x[j]=temp;
             }
         }
         temp=x[pivot];
         x[pivot]=x[j];
         x[j]=temp;
         quicksort(x,first,j-1,size);
         quicksort(x,j+1,last,size);
    }
}
}

OUTPUT OF THE PROGRAM


Quick Sort Algorithm
Quick Sort Algorithm