java 排序返回索引_java – 基于任意索引对数组进行排序

所以我知道如何对整数或浮点数(或其他数据类型)的

Java数组进行排序.但是,如果它是一个字符串数组String [] arr = {},其中数组包含像2x ^ 2,4x ^ 4这样的元素.如您所见,有几个具有整数的索引,可以对其进行排序.

我认为对此进行排序的方法是在索引处拼出数字.对这些数字进行排序,然后将每个旧索引映射到新索引.

我觉得有更好的方法.

基本问题:是否存在可以根据每个索引的特定索引处的整数对字符串数组进行排序的排序方法?

如果您想知道,这里将是算法的一些示例输入和输出.

Array: {"2x^3","2x^0","1x^1"}

Output:{"2x^3","1x^1","2x^0"} // Sorted based on last index

最佳答案

static final Comparator myComparator =

new Comparator() {

public int compare(String s1, String s2)

{

// split s1 and s2, compare what you need

// and return the result.

// e.g.

// char digit1 = s1[s1.length() - 1];

// char digit2 = s2[s2.length() - 1];

// return (int)(digit1 - digit2);

}

};

Collections.sort(list, myComparator);

// or

Arrays.sort(array, myComparator);

所以你让别人的排序方法为你做排序,你只需要提供一种方法来说明如何比较项目.您需要遵守一些规则和规定(例如,如果A< B,B< C,那么A必须是< C). 您也可以内联/匿名进行:

Collections.sort(list, new Comparator() {

public int compare(String s1, String s2) {

...

}

});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值