所以我遇到的问题是我已经编码了一种快速排序算法,并且确实可以工作。它始终按照从小到大的顺序对所有数字进行排序。但是,总是有两个项目应该在最后交换,我不确定在哪里实现交换。预先感谢。
#include <iostream>
#include <iomanip>
using namespace std;
void swap(double* a, double* b) {
double temp = *a;
*a = *b;
*b = temp;
}
int partition(double arr[], int start, int end) {
double pivot = arr[end];
int pivotIndex = start;
int index;
for (index = 0; index < end; index++) {
if (arr[index] < pivot) {
swap(arr[index], arr[pivotIndex]);
pivotIndex++;
}
}
swap(arr[pivotIndex], arr[index]);
return index;
}
void quickSort(double arr[], int start, int end) {
if (start < end) {
int part = partition(arr, start, end);
quickSort(arr, start, part - 1);
quickSort(arr, part + 1, end);
}
}
void main() {
double numList[10];
for (int i = 0; i < size(numList); i++) {
numList[i] = rand() % 100;
cout << setw(2) << left << numList[i] << " ";
}
cout << endl;
quickSort(numList, 0, size(numList) - 1);
for (int i = 0; i < size(numList); i++) {
cout << setw(2) << left << numList[i] << " ";
}
}
列表应使用该代码排序,但最后两项不会交换。
答案 0 :(得分:2)
您正在实现Lomuto分区方案,但是未正确正确地转录partition()。
int partition(double arr[], int start, int end) {
double pivot = arr[end];
int pivotIndex = start;
int index;
// Mistake 1: Start at the first element of the partition, not 0!
// for (index = 0; index < end; index++) {
for (index = start; index < end; index++) {
if (arr[index] < pivot) {
swap(arr[index], arr[pivotIndex]);
pivotIndex++;
}
}
// Mistake 2: Swap the last element of the partition.
// swap(arr[pivotIndex], arr[index]);
swap(arr[pivotIndex], arr[end]);
// Mistake 3: return the pivot index.
// return index;
return pivotIndex;
}