Description
数据很多,但我们经常只取前几名,比如奥运只取前3名。现在我们有n个数据,请按从大到小的顺序,输出前10个名数据。
Input
输入两行。
第一行一个整数n,表示要对多少个数据;
第二行有n个整数,中间用空格分隔。表示n个数据。
Sample Input
26 54 27 87 16 63 40 40 22 61 6 57 70 0 42 11 50 13 5 56 7 8 86 56 91 68 59
Output
输出一行,按从大到小排列的前10个数据,每个数据之间用一个空格隔开。
Sample Output
91 87 86 70 68 63 61 59 57 56
思路
首先我们看到这个问题会想到排序,排序有很多种(直接排序,冒泡排序,希尔排序,快速排序,选择排序,堆排序,归并排序),这里选择用了冒泡排序,其基本思想是:两两比较相邻记录,如果反序则交换,直到没有反序的记录为止。
代码:
c++:
#include<iostream>
using namespace std;
const int MaxSize=100;
class Sort{
public:
Sort();
void BubbleSort();
void Print();
private:
int data[MaxSize];
int length;
};
Sort::Sort(){
cin>>length;
for(int i=0;i<length;i++)
cin>>data[i];
}
void Sort::Print(){
for(int i=0;i<10;i++){
cout<<data[i]<<" ";
}
}
void Sort::BubbleSort(){
int i,exchange,bound,temp;
exchange=length-1;
while(exchange!=0){
bound=exchange;
exchange=0;
for(i=0;i<bound;i++)
if(data[i]<data[i+1]){
temp=data[i];
data[i]=data[i+1];
data[i+1]=temp;
exchange=i;
}
}
}
int main(){
Sort A;
A.BubbleSort();
A.Print();
return 0;
}
Java:
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[]a = new int[n];
for(int i = 0; i < n; i++){
a[i] = sc.nextInt();
}
for(int i = 0; i < n-1; i++){
for(int j = n-1; j > 0; j--){
if(a[j] > a[j-1]){
int temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
}
}
}
for(int i = 0; i < 10; i++){
System.out.print(a[i]+" ");
}
}
}