排序

来源:互联网 发布:三菱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);
原创粉丝点击