主流的排序方法有:冒泡排序、选择排序、希尔排序、堆排序等。
这里展示简单的冒泡排序法:
//冒泡排序(从大到小)
public class Bubble_Sort {
public static void main(String[] args) {
int score[] = {50, 80, 20, 60, 90, 70, 10, 40, 30, 100};
//定义10名同学的分数,打乱顺序,这里为了结果阅读方便简化了数字
int temp;
//冒泡排序
for(int i=0; i<10-1; i++) {
for(int j=0; j<10-1-i; j++) {
if(score[j]<score[j+1]) { //如果当前数小于下一个数
/*交换两个数的位置*/
temp = score[j];
score[j]=score[j+1];
score[j+1] = temp;
}
}
}
/*数组打印*/
for(int i=0;i<10;i++) {
System.out.print(score[i] + " " );
}
}
}
运行结果:
冒泡排序是最简单的排序方法,但是效率不高。主流排序方式的效率如下: