Acwing785.快速排序

Acwing785.快速排序

快排模板:

y总教学大法好~:

#include <iostream>

using namespace std;

const int N = 1000010;

int q[N];

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

    int i = l - 1, j = r + 1, x = q[l + 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()
{
    int n;
    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;
}


C++ STL快速算法:

#include <bits/stdc++.h>
using namespace std;
const int N=1000000+100;
int a[N],n,m,i,j;
int main()//C++ Stl使人快乐
{
    ios::sync_with_stdio(false);
    cin>>n;
    for(int i=1;i<=n;i++)
        cin>>a[i];
    sort(a+1,a+1+n);
    for(int i=1;i<=n;i++)
        cout<<a[i]<<" ";
    cout<<endl;
}

Acwing原题链接(https://www.acwing.com/problem/content/787/)
785.快速排序(链接同上)

练习题

786.第k个数(链接同上)

偷懒写法:

#include<iostream>
#include<algorithm>

using namespace std;

const int MAXN = 1e6+10;

long long int num[MAXN];
int n,k;

int main(){
    
    cin>>n>>k;
    for(int i  =0 ;i< n ;i++)
    {
        scanf("%d",&num[i]);
    }
    sort(num,num+n);
    cout<<num[k-1];
    
}

y总大法好~:
(小声bb:完全套模板,都不用思考的)

#include<iostream>
#include<algorithm>

using namespace std;

const int MAXN = 1e6+10;

long long int num[MAXN];
int n,k;

void quick_sort(long long int q[],int l,int r)
{
    if(l>=r)return ;
    
    int i = l - 1, j = r + 1, x = q[l + 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(){
    
    cin>>n>>k;
    for(int i  =0 ;i< n ;i++)
    {
        scanf("%d",&num[i]);
    }
    quick_sort(num,0,n-1);
    cout<<num[k-1];
    
}
posted @ 2020-03-21 14:14  libai1024  阅读(205)  评论(0编辑  收藏  举报