简体   繁体   中英

Lexicographic Quick Sort

I try to sort an array of Strings in lexicographical order by using the quick sort algorithm in java. The array is read in via the terminal using a Scanner and saved in an ArrayList . This ArrayList is later converted to an array where I (try to) apply the quick sort algorithm on. I have two methods:

private static void sortA(String[] s, int start, int end) {
    if (end > start) {
        int pivot = partition(s, start, end);
        sortA(s, start, pivot - 1);
        sortA(s, pivot + 1, end);
    }
}

private static int partition(String[] s, int start, int end) {
    String pivot = s[end];
    int left = start;
    int right = end;
    String temp = "";
    do {
        while ((s[left].compareTo(pivot) <= 0) && (left < end))
            left++;
        while ((s[right].compareTo(pivot) > 0) && (right > start))
            right--;
        if (left < right) {
            temp = s[left];
            s[left] = s[end];
            s[right] = temp;
            printRow(s);

        }
    } while (left < right);
    temp = s[left];
    s[left] = s[end];
    s[end] = temp;
    return left;
}

The code seems to randomly work fine and then suddenly not. For example the array {"java", "application", "system"} sorts fine to {"application", "java", "system"} . The array {"library", "content", "bin"} sorts to {"bin", "library", "contents"} , which is not the lexicographic order. Of course a computer does not work randomly so there must be something wrong with my code. I tried to work out an example on paper but then I'll find something completely wrong. However I based my code on an quick sort implementation of sorting a double array so I don't think I made a big reasoning error. Thanks in advance.

You are splitting the array in the wrong way: The correct splitting is "pivot-1" "pivot"

sortA(s, start, pivot-1);
sortA(s, pivot, end);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM