c++快速排序算法
題目描述
利用快速排序算法將讀入的NN個數從小到大排序后輸出。
快速排序是信息學競賽的必備算法之一。對於快速排序不是很了解的同學可以自行上網查詢相關資料,掌握后獨立完成。(C++選手請不要試圖使用STL
,雖然你可以使用sort
一遍過,但是你並沒有掌握快速排序算法的精髓。)
輸入輸出格式
輸入格式:
第11行為一個正整數NN,第22行包含NN個空格隔開的正整數a_ia**i,為你需要進行排序的數,數據保證了A_iA**i不超過10000000001000000000。
輸出格式:
將給定的NN個數從小到大輸出,數之間空格隔開,行末換行且無空格。
輸入輸出樣例
輸入樣例#1:
5
4 2 4 5 1
輸出樣例#1:
1 2 4 4 5
代碼及注釋
#include <iostream>
using namespace std;
void qsort(int, int);
int a[101];
int change(int,int);
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n;i ++)//輸入
{
cin >> a[i];
}
qsort(1, n);
for (int i = 1; i <= n;i ++)//輸出
{
cout << a[i] << " ";
}
// cout << endl;
// return 0;
}
void qsort(int l,int r)
{
int mid, p;// mid是中間值
int j, i;//i是左邊 j是右邊
i = l;
j = r;
mid = a[(l + r) / 2];//取中間的一個數
do
{
while (a[i] < mid)//如果指的數大於中間就停
{
i++;
}
while (a[j] > mid)//如果指的數小於中間就停
{
j--;
}
if (i <= j)//如果i在左邊; j在右邊
{
if (a[i] != a[j])//交換
{
p = a[i];
a[i] = a[j];
a[j] = p;
}
i++;//各自移動
j--;
}
} while (i <= j);
if (l < j)//排中間值左邊的
qsort(l, j);
if (i < r)//排中間值右邊的
qsort(i, r);
}
/*
9
3 5 8 1 2 9 4 7 6
*/
STL代碼
雖然題目上不允許用STL
但是
我還是用了
上代碼
#include <iostream>
#include <algorithm>//STL庫函數
using namespace std;
int main()
{
int arrays[100];
int n;
cin >> n;
for (int i = 1;i <= n;i ++)
{
cin >> arrays[i];
}
sort(arrays,arrays + n + 1);//STL排序函數
for (int i = 1;i <= n;i ++)
{
cout << arrays[i] << " ";
}
cout << endl;
return 0;
}