Sunday, January 29, 2012

QuickSort

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sort;

/**
 *
 * @author KAPILAN
 */
public class QuickSort {
    int[] num;
    int n;
    public QuickSort(int n){
        this.n=n;
       // p=0;q=n;
        num=new int[n+1];
        for(int i=0;i<n;i++){
            num[i]= (int) Math.round(Math.random()*n/2+1000);

        }
        num[n]=99999;
       // quickSort(0,n-1);
    }
    public void quickSort(){
     quickSort(0,n-1);
    }
 public void quickSort(int p,int q){
     int j;
     if(p<q){
            j=partition(p,q);
                quickSort(p,j-1);
                quickSort(j+1,q);

     }
 }

    private int partition(int p, int q) {
       int i=p;
       int j=q+1;
       int pivot=num[p];
       do{
           do{ i++;
           }while(num[i]<pivot);
        do{j--;
       }while(num[j]>pivot);
   
         if(i<j){
             swap(i,j);}
         }while(i<j);
       swap(p,j);
     
     
     return j;
}

    private void swap(int i, int i0){
        int temp=num[i];
        num[i]=num[i0];
        num[i0]=temp;
    }
    public void print(){
       
       
        for(int i=0;i<n;i++){
            System.out.print(num[i]+" ");
        }
    }
 
 public static void main(String []a){
      QuickSort s=new QuickSort(100);
       System.out.println("Before Sort");
       s.print();
       s.quickSort();
       System.out.println();
       System.out.println("after Sort");
       s.print();
 }
}
/*Before Sort
1033 1006 1047 1045 1004 1050 1008 1014 1004 1034 1044 1040 1016 1033 1038 1018 1004 1046 1002 1027 1026 1017 1023 1026 1049 1022 1013 1050 1046 1033 1009 1002 1026 1003 1047 1005 1003 1006 1042 1042 1029 1044 1003 1021 1025 1036 1009 1040 1047 1024 1007 1041 1044 1047 1004 1021 1025 1039 1007 1024 1043 1030 1017 1039 1043 1029 1019 1047 1049 1040 1013 1001 1039 1016 1017 1007 1018 1028 1010 1047 1033 1007 1042 1013 1050 1018 1005 1016 1028 1046 1022 1008 1039 1020 1040 1002 1024 1043 1042 1030
after Sort
1001 1002 1002 1002 1003 1003 1003 1004 1004 1004 1004 1005 1005 1006 1006 1007 1007 1007 1007 1008 1008 1009 1009 1010 1013 1013 1013 1014 1016 1016 1016 1017 1017 1017 1018 1018 1018 1019 1020 1021 1021 1022 1022 1023 1024 1024 1024 1025 1025 1026 1026 1026 1027 1028 1028 1029 1029 1030 1030 1033 1033 1033 1033 1034 1036 1038 1039 1039 1039 1039 1040 1040 1040 1040 1041 1042 1042 1042 1042 1043 1043 1043 1044 1044 1044 1045 1046 1046 1046 1047 1047 1047 1047 1047 1047 1049 1049 1050 1050 1050 */

No comments:

Post a Comment