1. 程式人生 > >【luogu 1177】【模板】快速排序

【luogu 1177】【模板】快速排序

sin 之一 快速排序 包含 names space 整數 -- 說明

題目描述

利用快速排序算法將讀入的N個數從小到大排序後輸出。

快速排序是信息學競賽的必備算法之一。對於快速排序不是很了解的同學可以自行上網查詢相關資料,掌握後獨立完成。(C++選手請不要試圖使用STL,雖然你可以使用sort一遍過,但是你並沒有掌握快速排序算法的精髓。)

輸入輸出格式

輸入格式:

輸入文件sort.in的第1行為一個正整數N,第2行包含N個空格隔開的正整數a[i],為你需要進行排序的數,數據保證了A[i]不超過1000000000。

輸出格式:

輸出文件sort.out將給定的N個數從小到大輸出,數之間空格隔開,行末換行且無空格。

輸入輸出樣例

輸入樣例#1:
5
4 2 4 5 1
輸出樣例#1:
1 2 4 4 5

說明

對於20%的數據,有N≤1000;

對於100%的數據,有N≤100000。

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<algorithm>
 4 #include<cstring>
 5 using namespace std;
 6 int n,a[100005];
 7 int read(){
 8     int x=0,f=1;char ch=getchar();
 9     while(ch<
0||ch>9){if(ch==-)f=-1;ch=getchar();} 10 while(ch>=0&&ch<=9){x=x*10+ch-0;ch=getchar();} 11 return x*f; 12 } 13 void q_sort(int l,int r){ 14 int i,j,mid;i=l,j=r; 15 mid=a[(i+j)/2]; 16 while(i<j){ 17 while(a[i]<mid) i++; 18 while
(a[j]>mid) j--; 19 if(i<=j) swap(a[i],a[j]),i++,j--; 20 } 21 if(l<j) q_sort(l,j); 22 if(i<r) q_sort(i,r); 23 } 24 int main(){ 25 n=read();for(int i=1;i<=n;i++)a[i]=read(); 26 q_sort(1,n); 27 for(int i=1;i<=n;i++) printf("%d ",a[i]); 28 return 0; 29 }

【luogu 1177】【模板】快速排序