Array sorting based on arbitrary index

So, I know how to sort a Java array from intsor floats(or other data types). But what if it was an array of strings String[] arr = {}, where such elements are contained in an array like 2x^2, 4x^4. As you can see, there are several indices with integers that can be sorted.

The way I think sorting this is to combine the number in the index. Sort these numbers, then map each old index to a new index.

I feel that there is a better way.

The essential question is: is there a sorting method that can sort a string array based on an integer with a specific index of each index?

If you're interested, there will be some sample inputs and outputs of the algorithm as such.

Array: {"2x^3","2x^0","1x^1"}
Output:{"2x^3","1x^1","2x^0"} // Sorted based on last index
+4
source share
1 answer
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 giving someone a sort sorting method for you, you just need to provide a method to tell how to compare the elements. There are some rules and regulations that must be followed (for example, if A <B, B <C, then A must be <C).

You can also do this inline / anonymously:

Collections.sort(list, new Comparator<String>() {
    public int compare(String s1, String s2) {
        ...
    }
 });
+2
source

Source: https://habr.com/ru/post/1620473/


All Articles