基于Java中的索引数组对数组进行排序(类似于C#的Array.Sort())

时间:2013-08-28 15:34:40

标签: java arrays sorting indexing

我正在尝试使用Java找到解决方案来执行以下操作。

int [] keys = new int[]{7,9,4,2,8,5,6,0}; // not necessarily a continuous series
double [] vals = new double[]{10,31,20,22,21,30,33,34}; // same length as keys<br/>

我需要对keys(从低到高)进行排序,并按顺序排列相应的vals。例如,这种情况的输出将是,

sorted keys:   0,  2,  4,  5,  6,  7,  8,  9
ordered vals: 34, 22, 20, 33, 10, 30, 21, 31

我无法使用地图,因为在某些计算中,我需要访问键和值,以提供keys[i]vals[j]等索引。

提前致谢,

7 个答案:

答案 0 :(得分:3)

创建一个包含字段键和值的类。然后实现Comparable接口。并覆盖compareTo方法。将列表中的对象放在一起,并将它们排序为:Collections.sort(list)

答案 1 :(得分:1)

您可以使用自定义冒泡排序来执行此操作。运行我的代码

public class IndexSort {

public static void main(String[] args) {
    int[] keys = new int[]{7, 9, 4, 2, 8, 5, 6, 0}; // not necessarily a continuous series
    double[] vals = new double[]{10, 31, 20, 22, 21, 30, 33, 34};
    for (int i = 0; i < keys.length; i++) {
        for (int j = i+1; j < keys.length; j++) {
            if(keys[i]>keys[j]){
                 int temp=keys[i];
                keys[i]=keys[j];
                keys[j]=temp;
                double t=vals[i];
                vals[i]=vals[j];
                vals[j]=t;
            }                
        }
        System.out.print(keys[i]+" -> ");
        System.out.println("  "+vals[i]);
    }
}
}

这是演示解决方案。为了提高性能,您应该将此逻辑应用于其他算法。

答案 2 :(得分:1)

您实际上可以创建一对,然后像这样排序

<强> Pair.java

class Pair
{
int key;
double val;

Pair()
{
}
Pair(int k,double v)
{
 key=k;
 val=v;
}
}

<强> Main.java

 class Main
    {
     public static void main(String ar[])
     {
      int [] keys = new int[]{7,9,4,2,8,5,6,0}; 
      double [] vals = new double[]{10,31,20,22,21,30,33,34};
      Pair p[]=new Pair[keys.length];   //length of any array
      for(int i=0;i<p.length;i++)
      {
         p[i] = new Pair(keys[i],vals[i]);
      }
      Collections.sort(p,new CustomComparator);
     }
    }

<强> CustomComparator.java

public class CustomComparator implements Comparator<Pair>
   {
      public int compare(Pair a, Pair b) {  
      if (a.key > b.key) {
         return 1;
      } else if (a.key < b.key) {
         return -1;
      }
      else
      return 0;
    }
}

答案 3 :(得分:0)

最简单的事情可能是首先将键/值对放入TreeMap,然后遍历该映射的Map.Entry条目并重写每个密钥对。在伪代码中:

sortedMap = new TreeMap

for i between 0 and keys.length
    sortedMap.put(keys[i], vals[i])

i = 0
for entry in sortedMap:
    keys[i] = entry.getKey()
    vals[i] = entry.getValue()
    ++i

答案 4 :(得分:0)

如果您没有重复的密钥(我假设您没有),那么将整个批次打入TreeMap

public static void main(String[] args) throws Exception {
    int[] keys = new int[]{7, 9, 4, 2, 8, 5, 6, 0};
    double[] vals = new double[]{10, 31, 20, 22, 21, 30, 33, 34};
    final Map<Integer, Double> m = new TreeMap<>();
    for (int i = 0; i < keys.length; ++i) {
        m.put(keys[i], vals[i]);
    }
    System.out.println(m);
}

输出:

{0=34.0, 2=22.0, 4=20.0, 5=30.0, 6=33.0, 7=10.0, 8=21.0, 9=31.0}
[34.0, 22.0, 20.0, 30.0, 33.0, 10.0, 21.0, 31.0]

Collection<Double> m.values()将根据您的需要进行订购。

或者在元组周围创建一个包装类,并对其中的List进行排序:

public static void main(String[] args) throws Exception {
    int[] keys = new int[]{7, 9, 4, 2, 8, 5, 6, 0};
    double[] vals = new double[]{10, 31, 20, 22, 21, 30, 33, 34};
    final class Wrapper implements Comparable<Wrapper> {

        final int key;
        final double value;

        public Wrapper(int key, double value) {
            this.key = key;
            this.value = value;
        }

        @Override
        public int compareTo(Wrapper o) {
            return Integer.compare(key, o.key);
        }

        @Override
        public String toString() {
            return "{key=" + key + ", value=" + value + "}";
        }
    }
    final List<Wrapper> wrappers = new ArrayList<>(keys.length);
    for (int i = 0; i < keys.length; ++i) {
        wrappers.add(new Wrapper(keys[i], vals[i]));
    }
    Collections.sort(wrappers);
    System.out.println(wrappers);
}

输出:

[{key=0, value=34.0}, {key=2, value=22.0}, {key=4, value=20.0}, {key=5, value=30.0}, {key=6, value=33.0}, {key=7, value=10.0}, {key=8, value=21.0}, {key=9, value=31.0}]

Collections.sort是一种稳定的排序,因此这将与重复项一起使用,并且不会更改其顺序。

答案 5 :(得分:0)

没有映射的最佳方法是在排序时更换keys数组的值时交换vals数组的元素。例如,使用插入排序:

private void insertionSort(int[] keys, int[] values){
    for(int i = 0; i < keys.length; i++){
        int key = keys[i];
        int val = values[i];
        int index = i;

        while(index > 0 && key < keys[index - 1]){
            keys[index] = keys[index - 1];
            values[index] = values[index - 1];
            index--;
        }

        keys[index] = key;
        values[index] = val;
    }

}

答案 6 :(得分:0)

这就是我如何做到并且有效:

  1. 创建一个implements Comparable
  2. 的键值对持有者类
  3. 将您的键值对类添加到列表中,并使用Collections.sort()对其进行排序。
  4. 示例:

    键值对类:

    /**
     * @author Buhake Sindi
     * @since 28 August 2013
     *
     */
    public class Pair implements Comparable<Pair> {
    
        private int key;
        private double value;
    
        /**
         * @param key
         * @param value
         */
        public Pair(int key, double value) {
            super();
            this.key = key;
            this.value = value;
        }
    
        /**
         * @return the key
         */
        public int getKey() {
            return key;
        }
    
        /**
         * @return the value
         */
        public double getValue() {
            return value;
        }
    
        /* (non-Javadoc)
         * @see java.lang.Comparable#compareTo(java.lang.Object)
         */
        public int compareTo(Pair o) {
            // TODO Auto-generated method stub
            if (getKey() > o.getKey()) {
                return 1;
            }
    
            if (getKey() < o.getKey()) {
                return -1;
            }
    
            return 0;
        }
    }
    

    测试用例:

    /**
     * @author Buhake Sindi
     * @since 28 August 2013
     *
     */
    public class PairComparer {
    
        public static void main(String[] args) {
            List<Pair> pairs = new ArrayList<Pair>(Arrays.asList(new Pair(7, 10d),
                                             new Pair(9, 31d),
                                             new Pair(4, 20d),
                                             new Pair(2, 22d),
                                             new Pair(8, 21d),
                                             new Pair(5, 30d),
                                             new Pair(6, 33d),
                                             new Pair(0, 34d)));
            Collections.sort(pairs);
            for (Pair pair : pairs) {
                System.out.println(pair.getKey() + " - " + pair.getValue());
            }
        }
    }
    

    输出:

    0 - 34.0
    2 - 22.0
    4 - 20.0
    5 - 30.0
    6 - 33.0
    7 - 10.0
    8 - 21.0
    9 - 31.0
    

    希望这有帮助。