A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

private static void sort(List<Integer> list) {
            
              Collections.sort(list);
      }
写了半天排序,忘记了api的强大

1 个回复

正序浏览
这道题是禁止使用Collections的sort方法的。看看我这个
  1. package com.itheima.test33;

  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.Random;

  5. /**
  6. * 编写程序,生成5个1至10之间的随机整数,存入一个List集合,
  7. * 编写方法对List集合进行排序(自定义排序算法,禁用Collections.sort方法和TreeSet)
  8. *
  9. * @author RuiWu
  10. */

  11. public class Test28 {

  12.         public static void main(String[] args) {
  13.                 List<Integer> list = new ArrayList<Integer>();
  14.                 for (int x = 0; x < 5; x++) {
  15.                         list.add(new Random().nextInt(10) + 1);
  16.                 }

  17.                 System.out.println(list);
  18.                 sortList(list);
  19.                 System.out.println(list);

  20.         }

  21.         private static void sortList(List<Integer> list) {
  22.                 for (int x = 0; x < list.size() - 1; x++) {
  23.                         for (int y = x + 1; y < list.size(); y++) {
  24.                                 if (list.get(x) > list.get(y)) {
  25.                                         int temp = list.remove(y);
  26.                                         list.add(y, list.get(x));
  27.                                         list.remove(x);
  28.                                         list.add(x, temp);
  29.                                 }
  30.                         }
  31.                 }
  32.         }
  33. }
复制代码


其实交换顺序也可以用Collections.swap(list,a,b),不过感觉也像是投机取巧。:lol
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马