AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

使用队列实现快速排序非递归

作者: 作者的头像   Ronin_56 ,  2024-11-28 16:22:51 ,  所有人可见 ,  阅读 3


0


// 使用队列实现快速排序非递归
#include <iostream>
#include <queue>
using namespace std;

// 快速排序中的一趟排序,返回基准值的索引
int partition(int arr[], int left, int right) {
    int pivot = arr[left]; // 选择最左边的元素作为基准
    while (left < right) {
        while (left < right && arr[right] >= pivot) {
            right--;
        }
        arr[left] = arr[right];
        while (left < right && arr[left] <= pivot) {
            left++;
        }
        arr[right] = arr[left];
    }
    arr[left] = pivot;
    return left;
}

// 快速排序非递归算法
void quickSortNonRecursive(int arr[], int left, int right) {
    queue<int> q;
    q.push(left);
    q.push(right);
    while (!q.empty()) {
        left = q.front();
        q.pop();
        right = q.front();
        q.pop();
        if (left < right) {
            int pivotIndex = partition(arr, left, right);
            q.push(left);
            q.push(pivotIndex - 1);
            q.push(pivotIndex + 1);
            q.push(right);
        }
    }
}

// 主函数,用于测试快速排序非递归算法
int main() {
    int arr[] = {10, 7, 8, 9, 1, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    quickSortNonRecursive(arr, 0, n - 1);
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    return 0;
}

0 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息