Java 带index信息排序(包含集合框架的使用)

来源:互联网 发布:微信爆粉引流加人软件 编辑:程序博客网 时间:2024/05/18 01:40

在进行排序的时候,我们一般得到的是排序后的结果。但是我们有时候不仅需要排序完的结果,还需要排序后对应原来序列的索引。毕图matlab中

[result, index] = sort(a)

result是排序后的结果,index为排序后对应得顺序索引
比如数组a = [1, 6, 3, 4],排序后result=[1, 3, 4, 6], index = [1, 3, 4, 2],即位置信息,6以前是第二个元素,现在排到第4个。
像Java、Python等基本都没有提供这个机制,对于Java,我们可以借助其集合框架来解决这个问题。

不允许有相同元素

使用TreeMap进行排序

 public static int[] sortAndOriginalIndex(Float[] arr) {    int[] sortedIndex = new int[arr.length];     TreeMap<Float, Integer> map = new TreeMap<Float, Integer>();        for (int i = 0; i < arr.length; i++) {       map.put(arr[i], i); // 将arr的“值-索引”关系存入Map集合     }  // System.out.println(map); // 打印集合看看//  System.out.println("打印格式 -- Value:Index");  // 使用Entry方式打印Map中的元素  int n=0;  Iterator<Map.Entry<Float, Integer>> it = map.entrySet().iterator();  while (it.hasNext()) {   Map.Entry<Float, Integer> me = it.next();//  System.out.print(me.getKey() + ":" + me.getValue() + "\t");      sortedIndex[n++] = me.getValue();  }  return sortedIndex; }

允许有相同元素

import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.TreeMap;public class TreeMapSort {    public static void main(String[] args) {        // TODO Auto-generated method stub        Map<Integer, String> map = new TreeMap<Integer, String>();        map.put(1, "ddddd");        map.put(2, "bbbbb");        map.put(3, "aaaaa");        map.put(4, "ccccc");        map.put(5, "aaaaa");        //这里将map.entrySet()转换成list        List<Map.Entry<Integer,String>> list = new ArrayList<Map.Entry<Integer,String>>(map.entrySet());        //然后通过比较器来实现排序        Collections.sort(list,new Comparator<Map.Entry<Integer,String>>() {            //升序排序            public int compare(Entry<Integer, String> o1,                    Entry<Integer, String> o2) {                return o1.getValue().compareTo(o2.getValue());            }        });        for(Map.Entry<Integer,String> mapping:list){                System.out.println(mapping.getKey()+":"+mapping.getValue());           }     }}####3:aaaaa5:aaaaa2:bbbbb4:ccccc1:ddddd
0 0
原创粉丝点击