冒泡排序
冒泡排序的算法运作如下
1.比较相邻的两个元素。如果第一个比第二个大,就交换他们两个
2.对每一个相邻的元素作同样的工作,从开始第一个到结尾的最后一对。最后的元素应该是最大的数
3.争对所有的元素重复以上的步骤,直到没有任何一对数字需要比较。
大家可以这样想,将下面的人按照身高从低到高重新排列
package cn.dct.oop;
import java.util.Arrays;
/**
* 测试冒牌排序
* @author Alex
*
*/
public class TestBubbleSort {
public static void main(String[] args) {
int[] values= {3,4,1,5,2,6,8,9,7};
int temp=0;
for (int i = 0; i < values.length; i++) {
boolean flag=true;
for (int j = 0; j < values.length-1-i; j++) {
//比较大小,换顺序
if(values[j]>values[j+1]) {
temp=values[j];
values[j]=values[j+1];
values[j+1]=temp;
flag=false;
}
System.out.println(Arrays.toString(values));
}
if(flag) {
System.out.println("结束=============");
break;
}
System.out.println("********************");
}
}
}
结果===============================================
[3, 4, 1, 5, 2, 6, 8, 9, 7]
[3, 1, 4, 5, 2, 6, 8, 9, 7]
[3, 1, 4, 5, 2, 6, 8, 9, 7]
[3, 1, 4, 2, 5, 6, 8, 9, 7]
[3, 1, 4, 2, 5, 6, 8, 9, 7]
[3, 1, 4, 2, 5, 6, 8, 9, 7]
[3, 1, 4, 2, 5, 6, 8, 9, 7]
[3, 1, 4, 2, 5, 6, 8, 7, 9]
[1, 3, 4, 2, 5, 6, 8, 7, 9]
[1, 3, 4, 2, 5, 6, 8, 7, 9]
[1, 3, 2, 4, 5, 6, 8, 7, 9]
[1, 3, 2, 4, 5, 6, 8, 7, 9]
[1, 3, 2, 4, 5, 6, 8, 7, 9]
[1, 3, 2, 4, 5, 6, 8, 7, 9]
[1, 3, 2, 4, 5, 6, 7, 8, 9]
[1, 3, 2, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
结束=============