2

Hi I'v been trying to write Hoare's partition function for like 5 hours now. I read this and this and even straight up copied the "correct" function from these questions and it's still nowhere near the answer. Here is my "translated" code from Cormen's book.

int Hpartition(int A[], int p, int r){
int x = A[p];
int i = p - 1;
int j = r + 1;
while(true){
    do{
        j--;
    }while(A[j] <= x);
    do{
        i++;
    }while(A[i] >= x);
    if(i < j){
        swap(A[i],A[j]);
    }
    else
        return j;
 }
}

QuickSort:

void qs(int A[],int p,int r){
if(p<r){
    int q=Hpartition(A,p,r);
    qs(A,p,q-1);
    qs(A,q+1,r);
}
}

Main:

int main(int argc, const char * argv[]) {
int tab[10];

for(int k=0;k<10;k++){
    cin >> tab[k];
}


qs(tab,0,9);

for(int i=0;i<10;i++){
    cout << tab[i] << " ";
}
return 0;
}

For this data :

2 4 1 3 5 7 6 8 10 9

It produces this result:

2 4 9 3 5 7 6 8 10 1

Based on the previous questions regarding the topic I know there may be some mistakes in the book. But even when I apply the answers from the previous questions it just won't work .

Here is the algorithm from the book:

HOARE-PARTITION(A, p, r)
1 x = A[p]
2 i = p - 1
3 j = r + 1
4 while TRUE
5     repeat
6        j = j - 1
7     until A[j] <= x
8     repeat
9        i = i + 1
10    until A[i] >= x
11    if i < j
12        exchange A[i] with A[j]
13    else return j

Thanks in advance for any help.

Community
  • 1
  • 1
  • `do..while` and `repeat..until` use inverted breaking conditions: `while(x)` repeats as long as `x` is true, `until(x)` stops, once `x` becomes true – BeyelerStudios Nov 11 '15 at 12:18

1 Answers1

1

You have 2 error translating code from book:

do{
     j--;
  }while(A[j] <= x);

You should inverse this:

do{
     j--;
  }while(A[j] > x);

The same with:

do{
     i++;
  }while(A[i] >= x);

And one more here:

qs(A,p,q-1);
qs(A,q+1,r);

Change to:

qs(A,p,q);
qs(A,q+1,r);
Giorgi Nakeuri
  • 33,698
  • 8
  • 33
  • 67