快速排序-分而治之

版权声明:博主的博客不值钱随便转载但要注明出处 https://blog.csdn.net/easylovecsdn/article/details/82873397
#include <bits/stdc++.h>

#define     max(x, y)      x >= y ? x : y
#define     min(x, y)      x <= y ? x : y

#define     INF     0x3f3f3f3f

using namespace std;

const int maxn = 105;    //数组最大尺寸105

int a[maxn];

void quicksort(int left, int right)
{
    if (right - left < 1) return ;

    int i = left;
    int j = right;
    int mid = (left + right) / 2;

    int temp = a[left];

    do {

        while (i < j && a[j] >= temp) j--;

        if (i < j) {
            a[i] = a[j];
            i++;
        }

        while (i < j && a[i] <= temp) i++;

        if (i < j) {
            a[j] = a[i];
            j--;
        }

    } while (i != j);

    a[i] = temp;

    quicksort(left, i-1);    //第i号位置是已经确定的位置,要做的就是将i号位子的左右两边分治
    quicksort(i+1, right);
}


void print(int Size)
{
    for (int i = 0; i < Size; i++) {
        if (i) cout << " ";
        cout << a[i];
    }
    cout << endl;
}

int main()
{
    int Size = 0;

    while (cin >> Size && Size) {

        for (int i = 0; i < Size; i++) cin >> a[i];

        quicksort(0, Size-1);

        print(Size);
    }

    return 0;
}

测试数据:

/*以下为测试数据

8
1 4 15 -3 6 12 -5 9


8
1 4 15 3 6 12 5 9
*/

结果:

猜你喜欢

转载自blog.csdn.net/easylovecsdn/article/details/82873397