試題 時間限制 快速排序(C++語言)
阿新 • • 發佈:2020-10-25
- 資源限制
時間限制:1.0s 記憶體限制:256.0MB - 問題描述
用遞迴來實現快速排序(quick sort)演算法。快速排序演算法的基本思路是:假設要對一個數組a進行排序,且a[0] = x。首先對陣列中的元素進行調整,使x放在正確的位置上。同時,所有比x小的數都位於它的左邊,所有比x大的數都位於它的右邊。然後對於左、右兩段區域,遞迴地呼叫快速排序演算法來進行排序。
輸入格式:輸入只有一行,包括若干個整數(不超過10個),以0結尾。
輸出格式:輸出只有一行,即排序以後的結果(不包括末尾的0)。 - 輸入輸出樣例
- 樣例輸入
5 2 6 1 7 3 4 0 - 樣例輸出
1 2 3 4 5 6 7
滿分程式碼如下:
#include<stdio.h>
void swap(int s[],int i,int j){
int temp;
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
void QuickSort(int s[],int low,int high){
int i;
int last;
if(low<high) {
last=low;
for(i=low+1;i<=high;i++){
if(s[i]<s[low])
swap(s,++last,i);
}
swap(s,last,low);
QuickSort(s,low,last-1);
QuickSort(s,last+1,high);
}
}
int main(){
int n,a[10],t,i=0;
while(scanf("%d",&n)&&n){
a[i++]=n;
}
QuickSort(a,0,i-1);
for(t=0;t<i;t++){
printf("%d ",a[t]);
}
return 0;
}