快速排序 C++
根據(jù)算法導(dǎo)論上的流程,將數(shù)組最后一個(gè)數(shù)作為主元,i和j都是從start往end移動(dòng)。
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; }如果,需要記錄原數(shù)組的位置標(biāo)記。下面的程序已數(shù)組的第一個(gè)為主元,i從start往后指示第一個(gè)大于主元的位置,j從end往前指示第一個(gè)小于主元的位置,每次交換數(shù)組的兩個(gè)位置的數(shù)據(jù),id記錄數(shù)組當(dāng)前的數(shù)據(jù)是未排序前數(shù)組的哪一項(xiàng)。
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; }
?
總結(jié)
- 上一篇: 可能是堆被损坏,这也说明 XX.exe
- 下一篇: c++连接mongodb出错