QuickSort and Hoare Partition

前端 未结 7 1179
轻奢々
轻奢々 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:26

    You last C code works. But it's not intuitive. And now I'm studying CLRS luckily. In my opinion, The pseudocode of CLRS is wrong.(At 2e) At last, I find that it would be right if changing a place.

     Hoare-Partition (A, p, r)
     x ← A[p]
         i ← p − 1
         j ← r + 1
     while  TRUE
            repeat   j ←  j − 1
                until     A[j] ≤ x
        repeat   i ←  i + 1
                until     A[i] ≥ x
        if  i < j
                  exchange  A[i] ↔ A[j]
        else  
                  exchnage  A[r] ↔ A[i]  
                  return   i
    

    Yes, Add a exchange A[r] ↔ A[i] can make it works. Why? Because A[i] is now bigger than A[r] OR i == r. So We must exchange to guarantee the feature of a partition.

提交回复
热议问题