背景:下面的代码是quickSort方法。该方法适用于有序列表,反向列表和随机列表。当我尝试使用quickSort并为参数“ first”传递随机整数以模拟随机splitPoint时,它会产生类似“ 9999 9998 9997 0 1 2 ... 9996”的输出(如果first为3,则将输出)
输入的是9999 9998 9997 ... 2 1 0
'a'是一个初始化的数组。
main.cpp
srand(time(0));
int randIndex = rand() % 10;
sort.quickSort(a, randIndex, 10);
sorting.cpp中的排序方法
//QuickSort an array given first and last.
void Sorting::quickSort(ItemType values[], int first, int last) {
if(first < last) {
int splitPoint;
split(values, first, last, splitPoint);
quickSort(values, first, splitPoint-1);
quickSort(values, splitPoint+1, last);
}
}
//Split an array given a split point.
void Sorting::split(ItemType values[], int first, int last, int& splitPoint) {
ItemType splitVal = values[first];
int saveFirst = first;
bool check;
first++;
do {
check = true;
while(check) {
if(values[first].compareTo(splitVal) == 0) {
count++;
check = false;
} else {
count++;
first++;
check = (first <= last);
}
}
check = (first <= last);
while(check) {
if(values[last].compareTo(splitVal) == 1 || values[last].compareTo(splitVal) == 2) {
count++;
check = false;
} else {
count++;
last--;
check = (first <= last);
}
}
if(first < last) {
count++;
swap(values[first], values[last]);
first++;
last--;
}
} while (first <= last);
splitPoint = last;
swap(values[saveFirst], values[splitPoint]);
}