views:

159

answers:

2

Possible Duplicate:
what is mistake in this code

i have following code from algorithm in c++

public class improved_quicksort {
    public static final int m=10;
    public static int partition(int a[],int l,int r){
        int i=l-1;
        int j=r;
        int v=a[r];
        while (true){
              while(a[++i]<v);
              while (a[--j]>v)  if (j==i)  break;
                if (i>=j)   break;
              exch(a,i,j);

        }
        exch(a,i,r);

        return i;
    }

    public static void quicksort(int a[],int l,int r){

         if ((r-l)<m)   return;
         exch (a,(l+r)/2,r-1);
          compex(a,l,r-1);
          compex(a,l,r);
          compex(a,r-1,r);

          int i=partition(a,l+1,r-1);
          quicksort(a,l,i-1);
          quicksort(a,i+1,r);
    }

    public static void compex(int a[],int i,int j){

         if (a[i]<a[j]){
             int t=a[i];
             a[i]=a[j];
             a[j]=t;
         }
    }

    public static void main(String[] args) {
      int a[]=new int[]{12,10,23,21,11,34,56,38,50,40,60,76,67};
      quicksort(a,0,a.length-1);
       for (int i=0;i<a.length;i++){
           System.out.println(a[i]);
       }
    }

    public static void exch(int a[],int i,int j){
         int k=a[i];
         a[i]=a[j];
         a[j]=k;
    }
}

but result is:

67
10
11
23
12
34
76
38
50
40
60
56
21
A: 

here is a good c++ quicksort page: http://orac.amt.edu.au/wiki/Quicksort

thomasfedb
A: 

Here is a quicksort routine I wrote some time ago. You may want to look at it as a reference.

public class InPlaceQuickSort {
    public int selectPivot(int[] arr, int low, int high) {
        return arr[low];
    }
    public void sort(int[] arr) {
        sort(arr, 0, arr.length - 1);
    }
    public void sort(int[] arr, int lowbound, int highbound) {
        if (lowbound >= highbound) return;
        int pivot = selectPivot(arr, lowbound, highbound);
        int low = lowbound, high = highbound;
        while (low <= high) {
            if (arr[low] > pivot) {
                swap(arr, low, high--);
            } else if (arr[high] < pivot) {
                swap(arr, low++, high);
            } else {
                low++; high--;
            }
        }
        sort(arr, lowbound, high);
        sort(arr, low, highbound);
    }

    /* swaps arr[a] with arr[b] */
    public void swap(int[] arr, int a, int b) {
        int tmp = arr[a];
        arr[a] = arr[b];
        arr[b] = tmp;
    }
} 
Lie Ryan
thanks very much
If anyone gave me the homework solution like that. AAAaah memories
laura
Please let people do their own homework. They will not learn anything if you do their homework for them.
Jesper