使用索引保留进行排序

时间:2012-07-02 14:12:59

标签: java sorting

而不是冒泡排序哪种排序技术可以用来对整数数组进行排序,这样在输出时我可以在原始数组中显示它的位置?

INPUT 4 5 3 6 1

输出

   INDEX : VALUE
     5   :   1
     3   :   3
     1   :   4
     2   :   5
     4   :   6

2 个答案:

答案 0 :(得分:5)

您可以使用TreeMap,其中键是数组中的值,值是索引+ 1。 它会自动完成您的需要。

示例代码:

public static void main(String[] args) throws ParseException {
    int[] array = new int[] {4, 5, 3, 6, 1};
    Map<Integer, Integer> sortedMap = new TreeMap<Integer, Integer>();

    for (int i = 0; i < array.length; i++) {
       sortedMap.put(array[i], i + 1);
    }
    System.out.println(sortedMap);
}

输出:

  

{1 = 5,3 = 3,4 = 1,5 = 2,6 = 4}

注意:这仅在原始列表中没有重复项时才有效

答案 1 :(得分:1)

持有者对象的解决方案:

public class IntWithIndex implements Comparable<IntWithIndex>
{
  public final Integer value;
  public final int index;

  public IntWithIndex(int value, int index) { 
    this.value = value; 
    this.index = index; 
  }

  public int compareTo(IntWithIndex other) { 
    return this.value.compareTo(other.value); 
  }
  public String toString() { 
    return String.format("[%d,%d]", value, index); 
  }

  public static void main(String[] args) {
    final IntWithIndex[] ts = new IntWithIndex[5];
    int i = 0;
    for (int x : new int[] { 4, 5, 3, 6, 1 }) 
      ts[i] = new IntWithIndex(x, i++);
    Arrays.sort(ts);
    System.out.println(Arrays.toString(ts));
  }
}
相关问题