There are many similar forms of quicksort.
You can randomly choose one pivot or two pivot to go while the code below only
deals with the single pivot case. Like the video, we burn the the candle from one side.
1. Candle burned from one side
- void quick_sort(int array[], int left, int right)
- {
- if (left < right)
- {
- // divide (partition)
- int pivot = array[(left+right)/2];
- // Can choose any number you want
- swap(array[right], array[(left+right)/2]);
- // to the rightmost
- int i = left, j = left;
- for (; j < right; ++j)
- if (array[j] <= pivot)
- {
- if (i < j) swap(array[i], array[j]);
- i = i + 1;
- }
- if (i < right) swap(array[i], array[right]);
- // then conquer
- quick_sort(array, left, i-1);
- quick_sort(array, i+1, right);
- // no need to combine sub-solutions
- }
- }
0 意見:
張貼留言