冒泡排序是算法中经典排序方法之一。名字也比较形象,因为整个过程可以看做是一堆泡泡向上飘,最终最轻的泡泡冒出来了(先不说物理规律……),第二趟扫描,“次轻”的泡泡冒上来,以此类推。
冒泡排序规则是 一个数组若有N项,那么会做出N-1 趟排序,才能够得到最终结果。比如数组score【】={3,5,1,8,2} 如按照从小到大的顺序,从左往右,3和5比较5大,不交换;5和1比较5大,则交换1和5的位置;以此类推,5和8,8和2,则第一趟排序就是把最大数置于最右边,因此每增加一次排序次数,就会减少一个需要比较的元素。
代码引用 自 http://www.cnblogs.com/wuzhenbo/archive/2012/03/30/2423861.html
1 public class BubbleSort{
2 public static void main(String[] args){
3 int score[] = {67, 69, 75, 87, 89, 90, 99, 100};
4 for (int i = 0; i < score.length -1; i++){
5 for(int j = 0 ;j < score.length - i - 1; j++){
6 if(score[j] < score[j + 1]){ //把小的值交换到后面
7 int temp = score[j];
8 score[j] = score[j + 1];
9 score[j + 1] = temp;
10 }
11 }
12 System.out.print("第" + (i + 1) + "次排序结果:");
13 for(int a = 0; a < score.length; a++){
14 System.out.print(score[a] + "\t");
15 }
16 System.out.println("");
17 }
18 System.out.print("最终排序结果:");
19 for(int a = 0; a < score.length; a++){
20 System.out.print(score[a] + "\t");
21 }
22 }
23 }引用