-2
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]);
    }

So for example in this I have the code printing out the array values from highest to lowest(4,3,2). However what I would like it to do is print the index/position of the array instead(2,0,1). Can't quite seem to figure it out myself, fairly new to this.

  • if you want to print index then just print i – Twinkle Patel Apr 03 '20 at 18:02
  • Similar to: [get-the-indices-of-an-array-after-sorting](https://stackoverflow.com/questions/4859261/get-the-indices-of-an-array-after-sorting) – Piotr Michalczyk Apr 03 '20 at 18:03
  • You are sorting the array and then printing it. You probably don't want to change the state of the array like that. See @PiotrMichalczyk comment for a better approach. – vsfDawg Apr 03 '20 at 18:05
  • For what I am doing I do want to change the state of my array to the index value instead @vsfDAWG – Sam West Apr 03 '20 at 18:12
  • Map the array to an array of pairs of (value, index), sort based on the value, then map back to an array of the indices. Aka Swartzian Tranform. – David Conrad Apr 03 '20 at 18:57

1 Answers1

0
/*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"
*/