转载请注明出处,谢谢!
冒泡排序算法思想:
- 自下而上(或上而下)扫描记录序列,相邻的两条记录
Ri
与Ri-1
(或Ri+1
)如果是逆序,则交换位置。
交换排序
- 冒泡排序
- 快速排序
算法说明
- 一个名声不太好的算法
- 排序是稳定的
ArrayList实现:
import java.util.ArrayList;
import java.util.Random;
public class Bubble {
public static void sort(ArrayList<Integer> al) {
int n = al.size();
for (int i = n - 1; i >= 0; i--) {
boolean flag = false;//若不发生交换了,以便提前结束算法。
for (int j = i ; j > 0; j--) {
if (al.get(j) < al.get(j-1)) {
Integer tempInt = al.get(j);
al.set(j, al.get(j-1));
al.set(j-1, tempInt);
flag = true;
}
}
System.out.println(al);
if (!flag)
break;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int n = 10;
ArrayList<Integer> al = new ArrayList<>(n);
// 创建一个随机数生成器
Random rand = new Random();
// 添加1-100的随机整数
for (int i = 0; i < n; i++) {
al.add(new Integer(Math.abs(rand.nextInt(100)) + 1));
}
System.out.println("The ArrayList Sort Before:\n" + al + "\nsorting:");
Bubble.sort(al);
}
}
Output:
The ArrayList Sort Before:
[39, 7, 8, 77, 61, 6, 3, 50, 81, 85]
sorting:
[3, 39, 7, 8, 77, 61, 6, 50, 81, 85]
[3, 6, 39, 7, 8, 77, 61, 50, 81, 85]
[3, 6, 7, 39, 8, 50, 77, 61, 81, 85]
[3, 6, 7, 8, 39, 50, 77, 61, 81, 85]
[3, 6, 7, 8, 39, 50, 77, 61, 81, 85]
——@guoyangde http://www.cnblogs.com/LittleTreasureBox/p/8904016.html
原文地址:https://www.cnblogs.com/LittleTreasureBox/p/8908539.html
时间: 2024-10-14 19:32:24