Последние два пункта в списке номеров не поменялись местами - PullRequest
0 голосов
/ 14 апреля 2019

Итак, у меня проблема в том, что я написал алгоритм быстрой сортировки, и он работает.Он последовательно сортирует все числа от наименьшего к наибольшему.Однако всегда есть два элемента, которые нужно поменять местами в самом конце, и я не уверен, где осуществить обмен.Заранее спасибо.

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

Список должен сортироваться по этому коду, но последние два элемента не меняются местами.

1 Ответ

2 голосов
/ 14 апреля 2019

Вы реализуете схему разделов Lomuto, но неправильно расшифровали раздел () правильно.

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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...