快排算法在分治的时候有两种实现,一种实现是从两边到中间(partition),另一种实现是从一边到另一边(partition2)。我用一个100000数组测试发现前一种实现运行速度快一些。
这两种的C++实现如下: (注:我用的代码风格是gnu的代码风格)
bool sort::qsort(int *ini, int start, int end) { // sort the array ini by ascending order int tmp=0; int mid=0; if (end < start){ return false; }else if(end == start){ if(ini[start] > ini[end]) { tmp = ini[start]; ini[start] = ini[end]; ini[end] = tmp; } return true; }else{ // when start is less end; mid = this->partition2(ini, start, end); // the partition fun. can either be partiton or partiton2. if(mid == start && qsort(ini,mid+1,end)) return true; if( mid == end && qsort(ini,start,mid-1)) return true; if(qsort(ini,start,mid-1) && qsort(ini,mid+1,end)) return true; return true; } } int sort::partition(int *ini, int start, int end) { // the main body for partition which from edge to middle int key=0; int i=start; int j=end; int tmp = 0; key = ini[i]; while(i!=j) { while(key <= ini[j] && i < j) j--; // exchange value, from right to left tmp = ini[i]; ini[i] = ini[j]; ini[j] = tmp; while(key >= ini[i] && i < j) i++; // exchange value, from left to right tmp = ini[i]; ini[i] = ini[j]; ini[j] = tmp; } return i; } int sort::partition2(int *ini, int start, int end) { // the main body for partition which from end to begin int key = ini[end]; int i = start - 1; // suppose the mid pos is i+1 int j=start; int tmp = 0; for(;j<end;j++) { if(ini[j] < key ) { i++; tmp = ini[i]; ini[i] = ini[j]; ini[j] = tmp; } } ini[end] = ini[i+1]; ini[i+1] = key; return i+1; }