Skip to content
本页目录

5快速排序-其它1

发布时间:

思想

  • 与最优版类似,不同之处 pivot选取数组中间位置,左边指针指向第一个。
  • 优点:根据指针交换完成后,不用单独交换pivot的位置。 -缺点,交换的次数相对最优的多。
js
#include <iostream>
using namespace std;

//中间位置选一个为中心轴 左右指针同时移动查找,交换。

int a[] = {3, 1, 7, 4, 9, 6, 2, 5, 8};
int len = sizeof(a) / sizeof(a[0]);
int pmoves = 0;
int swapNumber = 0;
void showA() {
    for (int i = 0; i < len; i++) {
        cout << a[i] << " ";
    }
    cout << endl;
}

void qsort(int l, int r) {
    int i, j, mid, p;
    i = l;
    j = r;
    mid = a[(l + r) / 2];  // 将当前序列在中间位置的数定义为分隔数
    cout << endl
         << a[mid] << " l:" << l << "r:" << r << endl;
    do {
        while (a[i] < mid) {
            pmoves++;
            i++;  // 在左半部分寻找比中间数大的数
        }
        while (a[j] > mid) {
            j--;  // 在右半部分寻找比中间数小的数
            pmoves++;
        }
        if (i <= j) {  // 若找到一组与排序目标不一致的数对则交换它们
         swap(a[i],a[j] );
            swapNumber++;
            i++;
            j--;
            pmoves++;
            pmoves++;
            showA();  // 继续找
        }
    } while (i <= j);  // 注意这里不能有等号
    if (l < j)
        qsort(l, j);  // 若未到两个数的边界,则递归搜索左右区间
    if (i < r)
        qsort(i, r);
}

int main() {
    qsort(0, len - 1);
    showA();
     cout << " 交换次数:" << swapNumber << endl;
    cout << " 指针移动数:" << pmoves << endl;
}

   

上次更新: