1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
void r_quick_sort_v2(int* list, int size, int pivot, int lo, int hi, bool was_moving_pivot_needed)
{
if ( lo == hi )//base case: when we have one elem => lo == hi
return;
// Else if ( !sort_needed ) return;//base case: *Q:can I add base case like use bb_sort to return bool to test if list is sorted w/ flag like if 1000000 itms so no need to waste memory w/ recursion and should check on current sublist rather than entire list again
else//Else sort L, R sublist, then move the pivot in place (Don't forget to update index of pivot)
{
while ( lo != hi || hi > lo)//go thru current list, do I really need this outer while loop?
{
while ( lo != hi )//search rightwards for a large elem or until end of this L sublist (=> no large elem found)
if ( list[lo] <= list[pivot] )
lo = lo + 1;
while ( hi != pivot )//search leftwards for a small elem, but if hi crosses lo, do last step: move pivot in place
{
if ( list[hi] > list[pivot] )
hi = hi - 1;
if ( list[hi] <= list[pivot] && (hi > lo) )//once we found the itm to swap w/ lo and hi hasn't crossed lo, then swap
{
int tmp = list[hi];
list[hi] = list[lo];
list[lo] = tmp; break;
}
if ( list[hi] <= list[pivot] && (hi <= lo))//if we found a smaller itm to replace w/ itm @ lo, BUT indx hi <= lo, then do last step: move pivot in place
{
if ( hi != pivot )//to prevent redundant moving pivot in place when it's already in place
{
int temporary = list[hi];
list[hi] = list[pivot];
list[pivot] = temporary;
pivot = hi; break;
was_moving_pivot_needed = true;
}
}
}
}
}//END else
//only sort L sublist if:
if ( was_moving_pivot_needed )
r_quick_sort_v2(list, size, 0, 0, pivot - 1, was_moving_pivot_needed);//break up list to a smaller R sublist to be sorted
//only sort R sublist if: pivot didn't have to move in place, i.e. pivot already in place so sort R sublist
else if ( !was_moving_pivot_needed )
r_quick_sort_v2(list, size, pivot + 1, pivot + 1, size - 1, was_moving_pivot_needed);//break up list to a smaller R sublist to be sorted
else//else there is a L, R sublist to sort
{
r_quick_sort_v2(list, size, 0, 0, pivot - 1, was_moving_pivot_needed);//break up list to a smaller L sublist to be sorted
r_quick_sort_v2(list, size, pivot + 1, pivot + 1, size - 1, was_moving_pivot_needed);//break up list to a smaller R sublist to be sorted
}
}
|