1

What is the best(fastest) way to sort an array of Strings (using Java 1.3).

0

2 Answers 2

5

You can use this code for sort the string values,

public Vector sort(String[] e) {
        Vector v = new Vector();
        for(int count = 0; count < e.length; count++) {
            String s = e[count];
            int i = 0;
            for (i = 0; i < v.size(); i++) {
                int c = s.compareTo((String) v.elementAt(i));
                if (c < 0) {
                    v.insertElementAt(s, i);
                    break;
                } else if (c == 0) {
                    break;
                }
            }
            if (i >= v.size()) {
                v.addElement(s);
            }
        }
        return v;
    }

Also see this sample code for using bubble sort,

static void bubbleSort(String[] p_array) throws Exception {
    boolean anyCellSorted;
    int length = p_array.length;
    String tmp;
    for (int i = length; --i >= 0;) {
        anyCellSorted = false;
        for (int j = 0; j < i; j++) {
            if (p_array[j].compareTo(p_array[j + 1]) > 0) {
                tmp = p_array[j];
                p_array[j] = p_array[j + 1];
                p_array[j + 1] = tmp;
                anyCellSorted = true;
            }

        }
        if (anyCellSorted == false) {
            return;
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

The first function (insertion sort) is not actually a sort: it drops duplicates due to the if (c == 0) break; clause.
0

Use java.util.Arrays.sort.

If it's not possible for some reason due to limitations of the platform, you can get ideas from its source.

Comments

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.