[英]Sorting Array based on an arbitrary index
So I know how to sort a Java array of ints
or floats
(or other data types). 所以我知道如何对
ints
或floats
(或其他数据类型)的Java数组进行排序。 But what if it was a string array String[] arr = {}
where the array contained elements like 2x^2
, 4x^4
. 但是,如果它是一个字符串数组
String[] arr = {}
,其中数组包含像2x^2
4x^4
这样的元素。 As you can see, there are several indices that have integers, which could be sorted. 如您所见,有几个具有整数的索引,可以对其进行排序。
The way I would think to sort this is to splice out the number at an index. 我认为对此进行排序的方法是在索引处拼出数字。 Sort those numbers, then map each old index to the new index.
对这些数字进行排序,然后将每个旧索引映射到新索引。
I feel like there is a better way. 我觉得有更好的方法。
The essential question: Does a sorting method exist that can sort a string array based on an integer at a certain index of each index? 基本问题: 是否存在可以根据每个索引的特定索引处的整数对字符串数组进行排序的排序方法?
If you are wondering, here would be some sample inputs and outputs of an algorithm as such. 如果您想知道,这里将是算法的一些示例输入和输出。
Array: {"2x^3","2x^0","1x^1"}
Output:{"2x^3","1x^1","2x^0"} // Sorted based on last index
static final Comparator<String> myComparator =
new Comparator<String>() {
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);
So you are letting someone else's sort method do the sorting for you, you just need to provide a method to say how to compare the items. 所以你让别人的排序方法为你做排序,你只需要提供一种方法来说明如何比较项目。 There are some rules and regulations you need to stick to (eg if A < B, B < C then A must be < C).
您需要遵守一些规则和规定(例如,如果A <B,B <C则A必须<C)。
You can also do it inline/anonymously: 您也可以内联/匿名进行:
Collections.sort(list, new Comparator<String>() {
public int compare(String s1, String s2) {
...
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.