一開始一樣設左邊起始值,和右邊起始值,
所以最右邊起始是從(right-1) 開始,
因為我把最右邊的值當作是pivot,
int right_index = right-1;
然後用無限迴圈來分配左邊比pivot小,右邊比pivot大。
一開始左邊是從left開始算起,直到第right數字,
如果遇到比pivot大的就跳掉,
while(left_index <= right && table[left_index]<pivot)
{
left_index++;
}
右邊是從(right-1)開始遞減,遇到比pivot小的就跳掉
while(right_index > left && table[right_index]>pivot)
{
right_index--;
}
然後這時的left_index和right_index,會是比pivot大和比pivot小的index,
就把這兩個值調換,
swap(&table[left_index], &table[right_index]);
如果left_index大於等於right_index代表已經交錯了,
就跳出迴圈,代比這次比完了,
if(left_index >= right_index)
break;
然後把pivot和left_index調換,因為要把pivot換到中間去,
分成左邊比pivot小,右邊比pivot大。
swap(&table[right], &table[left_index]);
然後左右兩邊再分別去做quick sort。
沒有留言:
張貼留言