
冒泡排序:
对于一组要排序的元素列,依次比较相邻的两个数,将比较小的数放在前面,比较大的数放在后面,如此继续,直到比较到最后的两个数,将小数放在前面,大数放在后面,重复步骤,直至全部排序完成。
public class MaoPao {
@Test
public void testMao(){
int[] arr1={19,85,5,32,4,56,20};
int index=arr1.length;
//记录目前序列是否已经是有序的
boolean so;
//记录经历了几轮,排序完成
int round=0;
for (int j = 1; j < index; j++) {
//初始化为true
so=true;
for (int i = 0; i < index-1; i++) {
if(arr1[i]>arr1[i+1]) {
//只要进入if就代表当前轮次不是有序的
so=false;
//交换数据
int tmp=arr1[i];
arr1[i]=arr1[i+1];
arr1[i+1]=tmp;
}else if(i==index-2){//当一轮排序结束,最高位就是最大值,需要排除在排序外
index--;
}
}
if(!so)
round++;
else break;
}
System.out.println("总轮次"+round);
for (int j : arr1) {
System.out.println(j);
}
}
}
-------------------------------------------------------------
结果:
总轮次4
4
5
19
20
32
56
85
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)