4

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
3
  • 3
    A lot of sorting methods let you provide a comparator, just set that up to "pick apart" your strings. Commented Dec 17, 2015 at 4:33
  • Some sample input and desired output might be helpful here. Commented Dec 17, 2015 at 4:33
  • @John3136: Could you be more specific? Commented Dec 17, 2015 at 4:38

1 Answer 1

2
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) {
        ...
    }
 });
Sign up to request clarification or add additional context in comments.

2 Comments

Thnx for your answer. I understand most of this, except what gets returned. Ex. The last digit of string 1 is higher than the last digit of string 2. What would be returned?
Top of my head: I can't remember ;-) It's easy enough to try digit1 - digit2, and if that doesn't work then it must be digit2 - digit1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.