在基于数组的存储中,要排序操作时,我们优先进行选择的我想就是Quicksort.
基本思想:找出分割枢轴,一趟排序将要排序的数据分割成两部分,这样一部分的所有数据都比另外一部分的所有数据都要小(大),然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
根据数组下标
template <class Record>
void Qsort(Record* array, int low, int high) {
//size > 2
if(low < high) {
int first = low;
int last = high;
//选取first做分割值
int key = array[first];
while(first < last) {
while(first < last && array[last] >= key) {
--last;
}
array[first] = array[last];
while(first < last && array[first] <= key) {
++first;
}
array[last] = array[first];
}
array[first] = key;
Qsort(array, low, first-1);
Qsort(array, first+1, high);
}
}
根据首尾指针:
template <class Record>
void quick_sort(Record* startPointer, Record* endPointer) {
if (startPointer < endPointer) {
Record *bottom = startPointer, *top = endPointer - 1;
Record privot = *startPointer;
while (bottom < top) {
while (bottom < top && *top >= privot) top--;
if (bottom < top) {
*bottom = *top;
bottom++;
}
while (bottom < top && *bottom <= privot) bottom++;
if (bottom < top) {
*top = *bottom;
top--;
}
}
*bottom = privot;
quick_sort(startPointer, bottom);
quick_sort(bottom + 1, endPointer);
}
}
说明:快排在最坏的情况是很糟糕的,因为我们选的都是first作为枢纽, 快排改进方法(点击)