根据算法导论上的流程,将数组最后一个数作为主元,i和j都是从start往end移动。
void QuickSort(T*source,size_t length){
if(!source){
return;
}
QSort(source,0,length-1);
}
template<typename T>
void Qsort(T*source,size_t start,size_t end){
if(start<end){
int pivot = Partition(source,start,end);
Qsort(source,start,pivot-1);
Qsort(source,pivot+1,end);
}
}
template<typename T>
size_t Partition( T*source, int start, int end ){
if(start>end || !source){
throw std::runtime_error("Invalid Input");
}
//T temp = source[start];
size_t i = start-1;
for(size_t j = start;j<end;j++){
if(source[j]<=source[end]){
i++;
swap(source[j],source[i]);
}
}
swap(source[i+1],source[end]);
return i+1;
}
如果,需要记录原数组的位置标记。下面的程序已数组的第一个为主元,i从start往后指示第一个大于主元的位置,j从end往前指示第一个小于主元的位置,每次交换数组的两个位置的数据,id记录数组当前的数据是未排序前数组的哪一项。
template <typename T>
void QuickSort( T*source, size_t* id, size_t length )
{
if(!source || length < 2)
return;
QSort( source, id, 0, length -1);
}
template <typename T>
void QSort( T*source, size_t* id, int start, int end )
{
if(start < end)
{
int pivot = Partition(source, id, start, end);
QSort(source, id, start, pivot-1);
QSort(source, id, pivot+1, end);
}
}
template <typename T>
size_t Partition( T*source, size_t* id, int start, int end )
{
if(start > end || !source)
throw std::runtime_error("Invalid Input");
T temp = source[start];
size_t tmpID = id[start];
while(start < end)
{
while(start < end && source[end] >= temp)
end--;
source[start] = source[end];
id[start] = id[end];
while(start < end && source[start] <= temp)
start++;
source[end] = source[start];
id[end] = id[start];
}
source[start] = temp;
id[start] = tmpID;
return start;
}

被折叠的 条评论
为什么被折叠?



