黑马程序员技术交流社区
标题:
求详细的分析解答过程
[打印本页]
作者:
dengxuye
时间:
2016-4-2 22:31
标题:
求详细的分析解答过程
编写程序,生成5个1至10之间的随机整数,存入一个List集合,
编写方法对List集合进行排序(自定义排序算法,不能用Collections.sort方法和TreeSet).
做了很久没有好做出来,求大神解答
作者:
994912025
时间:
2016-4-2 23:25
import java.util.ArrayList;
/*
* 需求:编写程序,生成5个1-10之间的随机数,存入一个List集合,编写方法对List集合进行排序(自定义排序算法,禁用COLLections.sort方法和TreeSet)然后遍历集合输出。
*/
public class Test006 {
public static void main(String[] args) {
// 创建集合对象
ArrayList<Integer> list = new ArrayList<Integer>();
// 随机产生5个随机数,并且存入集合
for (int x = 0; x < 5; x++) {
int temp = (int) (Math.random() * 10) + 1;
list.add(temp);
}
// 对集合进行排序
sortList(list);
// 遍历集合
printList(list);
}
// 选择排序算法
private static void sortList(ArrayList<Integer> list) {
for (int x = 0; x < list.size() - 1; x++) {
for (int y = x + 1; y < list.size(); y++) {
if (list.get(x) > list.get(y)) {
int temp1 = list.get(x);
int temp2 = list.get(y);
list.set(x, temp2);
list.set(y, temp1);
}
}
}
}
private static void printList(ArrayList<Integer> list) {
for (Integer i : list) {
System.out.print(i + " ");
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2