概念等其他的就不说了,耳根都。。。这个其他资料都说的很清楚了,理解起来也容易,关键是自己实现下,仔细的体会。
原来看到到实现随机找个元素作为比较的哨兵元素,数组的头部一个指针,尾部一个指针,头部开始向后,找到大于哨兵的,尾部开始向前,找到小于哨兵的,然后交换。前几天看到了一个要对链表进行快排的,由于单向链表的特殊性,没法从后像前,书里的这种方法可以用在链表上,《算法导论》上好像也是这种实现。
在书中所用的方法中,我们可以从头开始,也可以从尾开始,就是把哨兵放在头部,或者是放在尾部。
#define From_Front2Back
using namespace std;
int RandomRange(int start, int end)
{
return (start + rand()%(end - start));
}
template<class T>
int Partition(vector<T>& num, int start, int end){
if( start >= end)
return start;
int index = RandomRange(start, end);
#ifndef From_Head2Back
swap(num[index], num[end]);
int large = start;
int small = start - 1;
while (large < end)
{
//take care the && order.
if (num[large] < num[end] && ++small != large)
swap(num[small], num[large]);
++large;
}
swap(num[++small],num[end]);
return small;
#else
swap(num[index], num[start]);
int small = end;
int large = small + 1;
while(small > start){
if(num[small] > num[start] && --large != small)
swap(num[small], num[large]);
--small;
}
swap(num[start], num[--large]);
return large;
#endif
}
void quickSort(vector<int> &nums, int start, int end){
if(start >= end)
return;
int partitionIndex = Partition(nums, start, end);
if(partitionIndex > start)
quickSort(nums, start, partitionIndex - 1);
if(partitionIndex < end - 1)
quickSort(nums, partitionIndex + 1, end);
}
void main(){
const int numLength = 10;
const int range = 50;
vector<int> nums;
for (int i = 0; i < numLength; ++i)
nums.push_back(rand()%range);
quickSort(nums, 0, numLength - 1);
}