Quicksort C ++实现无法正常工作

时间:2014-03-15 20:26:33

标签: c++ quicksort

我正在尝试使用quicksort来处理整数数组但由于某种原因它没有正确排序。

#include <conio.h>
#include <iostream>

#include <stdlib.h>



using namespace std;
int partition(int * arr, int left, int right, int index);
int quicksort(int * arr, int left, int right);

int main(void){
    int arr[] = { 5,0,7,2,9,4,1,3,6,8 };


    quicksort(arr, 0, 9);
    for (int i = 0; i < 10; i++){
        cout << arr[i] << std::endl;
    }

}
int quicksort(int * arr, int left, int right){
    int pivot = 0;

    if (left < right){
        pivot = partition(arr, left, right, pivot);
            for (int i = left; i <= right; i++){
        cout << arr[i] << " ";
    }
    cout << std::endl;
        quicksort(arr, left, pivot - 1);
        quicksort(arr, pivot + 1, right);
    }
    return 0;
}

int partition(int *arr, int left, int right, int index){
    int pivotValue = arr[index];
    int storedIndex = left;
    int tmp;

    tmp = arr[index];
    arr[index] = arr[right];
    arr[right] = tmp;



    for (int i = left; i < right; i++){
        if (arr[i]<= pivotValue){
            tmp = arr[i];
            arr[i] = arr[storedIndex];
            arr[storedIndex] = tmp;


            storedIndex++;
        }
    }

    tmp = arr[storedIndex];
    arr[storedIndex] = arr[right];
    arr[right] = tmp;

    return storedIndex;





}

我在WikiPedia Quicksort上遵循了算法,但它仍然不起作用。我做错了什么?

0 2 4 1 3 5 8 9 6 7
0 2 4 1 3
0 4 1 2
1 3 4
2 9 6 8
6 7 9
8 0 1 3 4 5 2 6 7 9 
Press any key to continue . . .

1 个答案:

答案 0 :(得分:2)

您的pivot元素始终是数组的第一个元素。使用子数组调用quicksort或使用初始数据透视索引调用它。下面的代码是后者。

#include <iostream>
#include <stdlib.h>

using namespace std;
int partition(int *arr, int left, int right, int index);
int quicksort(int *arr, int left, int right, int pivot);

int main(void) {
  int arr[] = {5, 0, 7, 2, 9, 4, 1, 3, 6, 8};

  quicksort(arr, 0, 9, 0);
  for (int i = 0; i < 10; i++) {
    cout << arr[i] << std::endl;
  }
}
int quicksort(int *arr, int left, int right, int pivot) {
  //int pivot = 0;

  if (left < right) {
    pivot = partition(arr, left, right, pivot);

    quicksort(arr, left, pivot - 1, left);
    quicksort(arr, pivot + 1, right, pivot + 1);

  }
  return 0;
}

int partition(int *arr, int left, int right, int index) {
  int pivotValue = arr[index];
  int storedIndex = left;
  int tmp;

  tmp = arr[index];
  arr[index] = arr[right];
  arr[right] = tmp;

  for (int i = left; i < right; i++) {
    if (arr[i] <= pivotValue) {
      tmp = arr[i];
      arr[i] = arr[storedIndex];
      arr[storedIndex] = tmp;

      storedIndex++;
    }
  }

  tmp = arr[storedIndex];
  arr[storedIndex] = arr[right];
  arr[right] = tmp;

  return storedIndex;
}