最后两个数字列表中的项目没有交换

问题描述 投票:-2回答:1

所以我遇到的问题是我编写了一个快速排序算法,它确实有效。它始终将所有数字从最小到最大排序。但是,总有两个项目应该在最后交换,我不知道在哪里实现交换。提前致谢。

#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] << "  ";
    }
}

列表应该使用该代码排序,但最后两个项目不进行交换。

c++ sorting quicksort
1个回答
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.