Java中的排序

来源:互联网 发布:windows kill进程命令 编辑:程序博客网 时间:2024/05/18 05:41

Java中的可用于排序的包

import java.util.Collections;

        //使用Collections提供的对List的归并排序        //需实现其Comparator接口参数        Collections.sort(result, new Comparator<Recorder>() {            @Override            public int compare(Recorder o1, Recorder o2){                 //先比"coder"个数, count大者排前面                if(o1.getCount() != o2.getCount())                    return o2.getCount() - o1.getCount();                 //再比index, index小者排前面                else return o1.getIndex() - o2.getIndex();            }        });        String sorted[] = new String[result.size()];        for(int i=0;i<result.size();i++){            String s = result.get(i).getData();            sorted[i] = s;        }        return sorted;    }    class Recorder{        private String data; //字符串        private int index; //在原数组中的位置        private int count;  //含有多少个coder-1        public Recorder(String data, int index, int count){            this.data = data;            this.index = index;            this.count = count;        }        public String getData(){return data;}        public int getIndex(){return index;}        public int getCount(){return count;}    }

注意Collections.sort是采用的归并排序。

Collections.sort的compare函数要非常用心地写!

0 0