I’m working on a quick sort algorithm for a Huffman coding project I’m working on (explains why all the function names start with huff). When walking through it with the debugger, the function seems to freeze when finding the highest term (when trying to find the term from the right side of the vector which “should not” be on that side). There may (probable are) other problems with this code but i’m focussing on this one for now. By the way, most of the time (all of the time) I call cout, it’s for debugging purposes.
Edit: A lot of corrections have been made to my code from the comments, but none of them fix my problem. For that reason, I’m updating the code.
void huff_sort_partition(vector<Node*>* v, int b, int e){
int tempt = b+((rand()%(e-b))+1);
int p_idx = (*v)[tempt]->weight;
cout << tempt << endl;
int l = b+0;
int r = e;
cout << "P:" << p_idx << " L-R:" << l << "-" << r << endl;
while(l < r){
while((*v)[l]->weight < p_idx){
l++;
}
while((*v)[r]->weight > p_idx){
r--;
}
Node* s = (*v)[b+l];
(*v)[b+l] = (*v)[b+r];
(*v)[b+r] = s;
}
huff_sort_partition(v, b, l-1);
huff_sort_partition(v, l+1, e);
}
void Huff::huff_sort(vector<Node*>* v){
srand ( time(NULL) );
cout << "------sort------" << endl;
huff_sort_partition(v, 0, v->size());
}
Edit: I thought I’d add this since no one has answered this yet. If the code “should” work, then comment that (that way I can look for a reason outside this code for why it wont work).
Consider what happens in your code when there are several nodes with the pivot weight – for simplicity, consider the weights
[1, 9, 5, 2, 7, 5, 6, 8, 3, 7]and perchance the pivot index is 5, sowe have
p = 5l = 0andr = 91 < 5, then incrementl,l = 1,v[1] = 9 > 5.7 > 5, decrementr,r = 8,v[8] = 3 < 5. Swapv[1]andv[8], giving[1, 3, 5, 2, 7, 5, 6, 8, 9, 7].Next round,
l = 1 < 8 = r.v[1] = 3 < 5,lbecomes 2,v[2] = 5isn’t smaller than 5, end of loop. Now the second inner loop is entered,v[8] = 9 > 5,v[7] = 8 > 5,v[6] = 6 > 5;v[5] = 5isn’t larger than 5, swapv[2]andv[5], giving[1, 3, 5, 2, 7, 5, 6, 8, 9, 7].Next round,
l = 2 < 5 = r,v[2] = 5isn’t smaller than 5,v[5] = 5isn’t larger than 5, swapv[2]andv[5]. Oops, we’re stuck.The usual way to prevent this is to swap the pivot out of the way and have one of the two conditions a weak inequality, also one must check the condition
l < ralso in the inner loops, or in the case all entries are equal one would run off the end of the array/vector. Then after partitioning, one swaps the pivot into the right place.The following code uses the standard way (untested, typos possible):