排序
来源:互联网 发布:三菱m70cnc传输软件 编辑:程序博客网 时间:2024/06/07 15:47
选择排序:
public static void sort(int[] args) { int len = args.length; for (int i = 0, k = 0; i < len; i++, k = i) { // 在这一层循环中找最小 for (int j = i + 1; j < len; j++) { // 如果后面的元素比前面的小,那么就交换下标,每一趟都会选择出来一个最小值的下标 if (args[k] > args[j]) k = j; } if (i != k) { int tmp = args[i]; args[i] = args[k]; args[k] = tmp; } } }
冒泡排序:
public static void sortmaopao(int[] args) { for (int i = 0; i < args.length - 1; i++) { for (int j = 0; j < args.length - 1 - i; j++) { if (args[j] > args[j + 1]) { int temp = args[j]; args[j] = args[j + 1]; args[j + 1] = temp; } } } }
Comparator排序:重写compare方法
public static void main(String[] args) { int a[] = { 3, 2, 4, 1, 5 }; List<String> list = new ArrayList<String>(); for (int i = 0; i < a.length-1; i++) { list.add(a[i] + ""); } Collections.sort(list, new Comparator<String>() { public int compare(String a, String b) { // TODO Auto-generated method stub return Integer.parseInt(a) - Integer.parseInt(b); } }); }
实现Comparable接口:重写compareTo接口
public class Student implements Comparable<Student> { private String name; private int age; private float score; public Student(String name, int age, float score) { this.name = name; this.age = age; this.score = score; } public String toString() { return name + "\t\t" + age + "\t\t" + score; } public int compareTo(Student arg0) { // TODO Auto-generated method stub return arg0.age-this.age ; } public static void main(String[] args) { Student stu[] = { new Student("zhsan",26,90.0f), new Student("lisi", 22,90.0f), new Student("wangwu",25,99.0f), new Student("sunliu",21,100.0f) }; java.util.Arrays.sort(stu); for (Student s : stu) { System.out.println(s); } }}
Arrays.sort: 从小到大排序
Arrays.sort(number);
阅读全文
0 0
- 排序
- 排序
- 排序
- 排序
- 排序
- 排序
- 排序
- 排序
- 排序
- 排序
- 排序
- 排序
- 排序
- 排序
- 排序
- 排序
- 排序
- 排序
- 84. Largest Rectangle in Histogram
- 今日头条|张一鸣:我遇到的优秀年轻人的5个特质 头条招聘 2016-08-17 12:11 文| 张一鸣 今日头条|张一鸣:我遇到的优秀年轻人的5个特质 文章整理自今日头条张一鸣8月12日在“20
- 享元模式
- P1908 逆序对
- Hive中的join操作原理和优化
- 排序
- Python 07 函数的定义与调用
- 内置对象--Array对象篇
- cout不明确
- POJ3984《迷宫问题》
- POJ 2429 GCD & LCM Inverse(大整数素因子分解+二进制枚举)
- Qt网络编程--HTTP服务器(二)
- 依赖注入导致的空指针异常
- Node Web