快速排序板子(备战蓝桥杯)

题目:

活动 - AcWing

蓝桥杯省赛无忧班(C&C++ 组)第 4 期_蓝桥杯 - 蓝桥云课

【模板】排序 - 洛谷

板子:

复制代码
void quick_sort(int q[] , int l , int r)
{
    if(l >= r) return ;

    //这里的x 尽量折半查找 不然找左区间或者右区间可能会卡测试样例
    int x = q[l + r >> 1] , i = l - 1 ,j = r + 1;

    while(i < j)
    {
        do i++; while(q[i] < x);
        do j--; while(q[j] > x);

        if(i < j) swap(q[i],q[j]);
    }

    quick_sort(q,l,j);
    quick_sort(q,j+1,r);
}

题解:

复制代码
#include<cstdio>
#include<iostream>
#include<algorithm>

using namespace std;

const int N = 1e6 + 10;
int n;
int q[N];

void quick_sort(int q[] , int l , int r)
{
    if(l >= r) return ;

    //这里的x 尽量折半查找 不然找左区间或者右区间可能会卡测试样例
    int x = q[l + r >> 1] , i = l - 1 ,j = r + 1;

    while(i < j)
    {
        do i++; while(q[i] < x);
        do j--; while(q[j] > x);

        if(i < j) swap(q[i],q[j]);
    }

    quick_sort(q,l,j);
    quick_sort(q,j+1,r);
}

int main()
{
    scanf("%d",&n);

    for(int i = 0 ; i < n ; i++) scanf("%d",&q[i]);

    quick_sort(q,0,n-1);

    for(int i = 0 ; i < n ; i++) printf("%d ",q[i]);
    return 0;
}
相关推荐
搬砖魁首8 小时前
基础能力系列 - 多线程2 - 条件变量
c++·rust·条件变量·原子类型·线程同步互斥
chase_my_dream9 小时前
C++ + SLAM 高频面试问题整理
开发语言·c++·面试
牛油果子哥q9 小时前
【C++ STL string 】C++ STL string 终极精讲:底层原理、内存机制、全套API、深浅拷贝、易错坑点与工程实战规范
数据库·c++
凡人叶枫11 小时前
Effective C++ 条款04:确定对象被使用前已先被初始化
java·linux·开发语言·c++·嵌入式开发
不想写代码的星星11 小时前
std::move 根本不移动,就像老婆饼里没有老婆
c++
redaijufeng11 小时前
C++雾中风景7:闭包
c++·算法·风景
小欣加油12 小时前
leetcode287寻找重复数
数据结构·c++·算法·leetcode
思麟呀12 小时前
C++11 核心特性(三):强类型枚举、static_assert 与 std::tuple
开发语言·c++
一拳一个呆瓜12 小时前
【STL】C++程序的启动与终止
c++·stl
凡人叶枫12 小时前
Effective C++ 条款07:为多态基类声明 virtual 析构函数
linux·c语言·开发语言·c++