public class Demo {
/*
* 编写程序,生成5个1至10之间的随机整数,存入一个List集合,编写方法对List集合进行排序(自定义排序算法,禁用Collections.
* sort方法和TreeSet),然后遍历集合输出
*/
public static void main(String[] args) {
// 定义一个集合
ArrayList<Integer> arrList = new ArrayList<Integer>();
// 向集合中添加数据
for (int i = 0; i < 5; i++) {
arrList.add(new Random().nextInt(10) + 1);
}
System.out.println("元集合:" + arrList);
bubleSort(arrList);
// listSort(arrList);
System.out.println("排序后:" + arrList);
}
// 冒泡排序
private static void bubleSort(ArrayList<Integer> arrList) {
for (int i = 0; i < arrList.size(); i++) {
for (int j = 0; j < arrList.size() - i - 1; j++) {
if (arrList.get(j) > arrList.get(j + 1)) {
int temp = arrList.get(j);
arrList.set(j, arrList.get(j + 1));
arrList.set(j + 1, temp);
}
}
}
}
// 选择排序
private static void selectSort(ArrayList<Integer> arrList) {
for (int i = 0; i < arrList.size(); i++) {
for (int j = i + 1; j < arrList.size(); j++) {
if (arrList.get(i) > arrList.get(j)) {
int temp = arrList.get(i);
arrList.set(i, arrList.get(j));
arrList.set(j, temp);
}
}
}
}
}
|
|