[英]How to print sorted array index instead of the value in Java?
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).所以例如在这个我有代码打印出从最高到最低(4,3,2)的数组值。 However what I would like it to do is print the index/position of the array instead(2,0,1).但是我想做的是打印数组的索引/位置(2,0,1)。 Can't quite seem to figure it out myself, fairly new to this.我自己似乎不太明白,对此相当陌生。
/*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"
*/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.