洛 谷 -P1177 【Template】 Quick sort

洛 谷 -P1177 【Template】 Quick sort

Original title link: https://www.luogu.com.cn/problem/P1177


Title description

Use the quick sort algorithm to sort the N numbers read in from small to large and output.

Quick sorting is one of the necessary algorithms for informatics competitions. Students who are not familiar with quick sorting can check the relevant information online and complete it independently after mastering it. (C ++ players do not attempt to use STL, although you can use sortover and over, but you did not grasp the essence of fast sorting algorithm.)

Input format

The first line is a positive integer N, and the second line contains N space-separated positive integers \ (a_i \) , the number you need to sort, the data guarantees that \ (A_i \) does not exceed \ (10 ​​^ 9 \ ) .

Output format

Output the given N numbers from small to large, separated by spaces, and wrap at the end of the line without spaces.

Sample input and output

Enter # 1

5
4 2 4 5 1
Output # 1
1 2 4 4 5

Instructions / Tips

For 20% of the data, there is \ (N \ leq 10 ^ 3 \) ;

For 100% data, there is \ (N \ leq 10 ^ 5 \) .

C ++ code

#include <iostream>
using namespace std;

void quickSort(int a[], int l, int r) {
    int i=l,j=r,mid=a[(l+r)/2];
    while(i<=j) {
        while(a[i]<mid) i++;
        while(a[j]>mid) --j;
        if(i<=j)
            swap(a[i++],a[j--]);
    }
    if(l<j) quickSort(a,l,j);
    if(i<r) quickSort(a,i,r);
}

int main() {
    int n,i;
    cin>>n;
    int a[n];
    for(i=0;i<n;++i)
        cin>>a[i];
    quickSort(a,0,n-1);
    for(i=0;i<n;++i)
        cout<<a[i]<<' ';
    cout<<endl;
    return 0;
}

Guess you like

Origin www.cnblogs.com/yuzec/p/12749642.html