java中怎么打印最小值_java – 如何在数组中打印10个最小值的索引

It was the smallest numbers but I lost indexes of this values, which

they had i non-sorted array

那你为什么不创建一个类来保存这个索引呢?

然后只需按值对数组进行排序,您就可以获得索引关联.

class MyClass implements Comparable{

private int index;

private int value;

public MyClass(int i, int v){

this.index = i;

this.value = v;

}

@Override

public String toString(){

return "Index: "+index+" Value: "+value;

}

@Override

public int compareTo(MyClass m) {

return value - m.value;

}

}

public static void main(String[] args){

MyClass[] array = new MyClass[20];

for(int i = 0; i < array.length; i++){

array[i] = new MyClass(i, someRandomValue); // Here I used (i*3 + 2)%5

}

System.out.println(Arrays.toString(array));

Arrays.sort(array);

MyClass [] arraySorted = Arrays.copyOfRange(array, 0, 10); //take the first ten elements

System.out.println(Arrays.toString(arraySorted));

}

注意 :

如果要按索引对具有相同值的对象进行排序,可以像这样修改比较器:

@Override

public int compareTo(MyClass m) {

int compareValue = value - m.value;

if(compareValue == 0)

return index - m.index;

return compareValue;

}

输出(使用第二个compareTo方法):

Before :

[Index: 0 Value: 2, Index: 1 Value: 0, Index: 2 Value: 3, Index: 3 Value: 1, Index: 4 Value: 4, Index: 5 Value: 2, Index: 6 Value: 0, Index: 7 Value: 3, Index: 8 Value: 1, Index: 9 Value: 4, Index: 10 Value: 2, Index: 11 Value: 0, Index: 12 Value: 3, Index: 13 Value: 1, Index: 14 Value: 4]

After :

[Index: 1 Value: 0, Index: 6 Value: 0, Index: 11 Value: 0, Index: 3 Value: 1, Index: 8 Value: 1, Index: 13 Value: 1, Index: 0 Value: 2, Index: 5 Value: 2, Index: 10 Value: 2, Index: 2 Value: 3]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值