intboolstring
intboolstring

Reputation: 7100

Sorting Array based on an arbitrary index

So I know how to sort a Java array of ints or floats (or other data types). But what if it was a string array String[] arr = {} where the array contained elements like 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

Upvotes: 4

Views: 341

Answers (1)

John3136
John3136

Reputation: 29266

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 (e.g. if A < B, B < C then A must be < C).

You can also do it inline/anonymously:

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

Upvotes: 2

Related Questions