英文:
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(i);
}
在这个代码中,我已经修改了最后一个循环,以便打印出数组元素的索引/位置(2, 0, 1),而不是值。
英文:
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.
答案1
得分: 0
/*可以创建一个类,如下所示:*/
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){
IndexAndValue temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
for(int i = 0; i < array.length; i++) {
System.out.println("索引: " + array[i].index + " 值: " + array[i].value);
}
/*
当您执行此代码时,会得到:
"索引: 2 值: 4"
"索引: 0 值: 3"
"索引: 1 值: 2"
*/
英文:
/*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"
*/
专注分享java语言的经验与见解,让所有开发者获益!
评论