C ++ - 实现Quicksort的问题

时间:2016-06-02 14:47:24

标签: c++ algorithm sorting recursion quicksort

所以我是递归的新手,我试图实现一些算法,比如下面的quicksort,但它似乎没有那么好......我认为问题出在分区,但我我不确定问题是什么......

#include <iostream>

using namespace std;

const int MAX = 100;

typedef int matrix[MAX];

struct Taula{
    matrix m;
    int n;
};
void wwap(Taula &t, int n, int i, int posPivot)
{
    int aux = t.m[posPivot];
    t.m[posPivot] = t.m[i];
    t.m[i] = aux;
}
void partition(Taula &t, int n, int left, int right, int &posPivot)
{
    int pivot = t.m[right];
    posPivot = left;
    for (int i = left; i < right-1; i++){
        if (t.m[i] < pivot){
            swap(t,n,i,posPivot);
            posPivot = posPivot+1;
        }
    }
    swap(t,n,posPivot,right);
}
void quicksort(Taula &t, int n, int left, int right)
{
    int k;
    if (left < right){
        particio(t,t.n,left,right,k);
        quicksort(t,t.n,left,k-1);
        quicksort(t,t.n,k+1,right);
    }
}

int main()
{
    Taula t;
    t.n = 0;

    cout << "INTEGER SEQUENCE ENDED WITH -2:" << endl;
    int x; cin >> x;

    while (x != -2){
        t.m[t.n] = x;
        t.n++;
        cin >> x;
    }
    cout << t.n << " ELEMENTS" << endl;
    quicksort(t,t.n,0,t.n);
    cout << "SORT:" << endl;
    for (int i = 0; i < t.n; i++) cout << t.m[i] << endl;
    return 0;
}

这将是一个输出示例:

INTEGER SEQUENCE ENDED WITH -2:
45
-4
-9
-3
13
64
789
-645
78
-62
12
35
-14
6
0
21
-5
454
-2
18 ELEMENTS
SORT:
-645
-14
-9
-62
-5
-3
-4
0
12
6
13
35
45
64
78
789
21
4254617

Process returned 0 (0x0)   execution time : 31.583 s
Press any key to continue.

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

你必须从左边开始,直到找到比你的枢轴更大的数字,而不是从右到左,直到你找到一个更低的数字......(这两个循环使快速排序非常快......)看看这段代码...

https://en.wikibooks.org/wiki/Algorithm_Implementation/Sorting/Quicksort

你需要这两行:

while Array[L2] < PivotValue do // scan left partition
    L2 := L2 + 1;
while Array[R2] > PivotValue do // scan right partition
    R2 := R2 - 1;

所以这是你的问题:

for (int i = left; i < right-1; i++){
    if (t.m[i] < pivot){
        swap(t,n,i,posPivot);
        posPivot = posPivot+1;
    }
}

答案 1 :(得分:0)

您正在使用Lomuto分区方法。正确的方法:

  for (int i = left; i <= right-1; i++){
        if (t.m[i] <= pivot){
            swap(t,n,i,posPivot);
            posPivot = posPivot+1;
        }

第二个问题 - 主要应该是:

 quicksort(t,t.n,0,t.n - 1);