QuickSort and Hoare Partition

前端 未结 7 1191
轻奢々
轻奢々 2020-12-01 14:33

I have a hard time translating QuickSort with Hoare partitioning into C code, and can\'t find out why. The code I\'m using is shown below:

void QuickSort(in         


        
7条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 15:21

    Your final code is wrong, since the initial value of j should be r + 1 instead of r. Otherwise your partition function always ignore the last value.

    Actually, HoarePartition works because for any array A[p...r] which contains at least 2 elements(i.e. p < r), every element of A[p...j] is <= every element of A[j+1...r] when it terminates. So the next two segments that the main algorithm recurs on are [start...q] and [q+1...end]

    So the right C code is as follows:

    void QuickSort(int a[],int start,int end) {
        if (end <= start) return;
        int q=HoarePartition(a,start,end);
        QuickSort(a,start,q);
        QuickSort(a,q + 1,end);
    }
    
    int HoarePartition (int a[],int p, int r) {
        int x=a[p],i=p-1,j=r+1;
        while (1) {
            do  j--; while (a[j] > x);
            do  i++; while (a[i] < x);
            if  (i < j) 
                swap(&a[i],&a[j]);
            else 
                return j;
        }
    }
    

    More clarifications:

    1. partition part is just the translation of the pseudocode. (Note the return value is j)

    2. for the recursive part, note that the base case checking (end <= start instead of end <= start + 1 otherwise you will skip the [2 1] subarray )

提交回复
热议问题