## 代码模板
void quick_sort(int q[], int l, int r)
{
if (l >= r) return;// 判断排序的数字长度
int i = l - 1, j = r + 1, x = q[l];
//选取双指针i,j与 中间随机值
while (i < j)
{
//进行判断比较大小并交换值
do i ++ ; while (q[i] < x);
do j -- ; while (q[j] > x);
if (i < j) swap(q[i], q[j]);
//注意!!!使用语言有没有swap方法(如果没有建议用位运算)
else break;
}
//再将俩个部分(小于等于随机值||大于小于随机值)再次划分
quick_sort(q, l, j),;
quick_sort(q, j + 1, r);
}
785. Quick Sort
You are given a sequence of integers of length n.
Please use quick sort to sort this sequence from small to large.
and output the sorted arrays in order.
input format
The input consists of two lines, the first line contains the integer n.
The second line contains n integers (all in the range 1 to 109109), representing the entire sequence.
output format
The output is one line, containing n integers, representing a sorted sequence.
data range
1≤n≤1000001≤n≤100000
Input sample:
5
3 1 2 4 5
Sample output:
1 2 3 4 5
Code:
#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1e6 + 10;
int a[N];
void quick_sort(int a[], int l, int r){
if(l >= r) return ;
int i = l - 1;
int j = r + 1;
int x = a[l];
while(i < j){
do i++ ; while(a[i] < x);
do j-- ; while(a[j] > x);
if(i < j) swap(a[i], a[j]);
else break;
}
quick_sort(a, l, j);
quick_sort(a, j + 1, r);
}
int main(){
int n;
scanf("%d",&n);
for(int i = 1; i <= n; i++){
scanf("%d",&a[i]);
}
quick_sort(a, 1, n);
for(int i = 1; i <= n; i++){
if(i != n) printf("%d ", a[i]);
else printf("%d\n", a[n]);
}
return 0;
}