【问题标题】:How to print sorted array index instead of the value in Java?如何打印排序数组索引而不是Java中的值?
【发布时间】:2020-04-03 17:57:54
【问题描述】:
int[] array = new int[3];
    array[0] = 3;
    array[1] = 2;
    array[2] = 4;

    for(int i = 0 ; i < array.length;i++){
        for(int j = i+1 ; j< array.length;j++){
            if(array[i] < array[j]){
                int temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }
}
    for(int i=0; i<array.length; i++) {
    System.out.println(array[i]);
    }

例如,在此我有代码打印出从最高到最低的数组值(4,3,2)。但是我想做的是打印数组的索引/位置(2,0,1)。我自己似乎不太明白,对此相当陌生。

【问题讨论】:

  • 如果你想打印 index 然后打印 i
  • 您正在对数组进行排序,然后打印它。您可能不想像那样更改数组的状态。请参阅@PiotrMichalczyk 评论以获得更好的方法。
  • 对于我正在做的事情,我确实想将数组的状态更改为索引值而不是@vsfDAWG
  • 将数组映射到 (value, index) 对的数组,根据值排序,然后映射回索引数组。 Aka Swartzian 变换。

标签: java arrays sorting indexing


【解决方案1】:
/*you can create a new class lik that :*/

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


  IndexAndValue[] array = new IndexAndValue[3];  
    array[0] = new IndexAndValue(0 ,2);
    array[1] = new IndexAndValue(1 ,2);
    array[2] = new IndexAndValue(2 ,4);

   for(int i = 0 ; i < array.length;i++){
        for(int j = i+1 ; j< array.length;j++){
            if(array[i].value < array[j].value){
                int temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }
    }
    for(int i=0; i<array.length; i++) {
     System.out.println("Index : " +array[i].index +" value: " +array[i].value);
    }

/*
whene you exucte this you get :
"Index : 2 value: 4"
"Index : 0 value: 3"
"Index : 1 value: 2"
*/

【讨论】:

    猜你喜欢
    • 2021-05-23
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 2012-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多