栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Java中对数组进行排序并跟踪索引

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Java中对数组进行排序并跟踪索引

尝试对

(value, index)
按值比较的对进行排序:

public class Pair implements Comparable<Pair> {    public final int index;    public final int value;    public Pair(int index, int value) {        this.index = index;        this.value = value;    }    @Override    public int compareTo(Pair other) {        //multiplied to -1 as the author need descending sort order        return -1 * Integer.valueOf(this.value).compareTo(other.value);    }}

然后,当您要排序时:

public static void main(String[] args) {    Pair[] yourArray = new Pair[10];    //fill the array    yourArray[0] = new Pair(0, 5); yourArray[1] = new Pair(1, 10); //and so on    Arrays.sort(yourArray);}

现在,您具有

Pair
value
降序排列的对象数组。每个对象还包含
index
-原始数组中的位置。

PS:我用Java编写了示例,因为问题带有

java
标签。尽管在
C++
思想上是相同的,但是只有实现有所不同。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/470183.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号