CodexBloom - Programming Q&A Platform

Unexpected Behavior of Quicksort with Custom Comparator in Java - Inconsistent Sorting Results

πŸ‘€ Views: 1293 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-05
sorting algorithm quicksort comparator Java

This might be a silly question, but I'm experiencing unexpected behavior while implementing the Quicksort algorithm in Java using a custom comparator... My goal is to sort a list of strings based on their lengths and, in the case of ties, alphabetically. However, I'm getting inconsistent sorting results, particularly when the list contains strings of the same length. Here’s a simplified version of my code: ```java import java.util.Arrays; import java.util.Comparator; public class CustomQuicksort { public static void main(String[] args) { String[] arr = {"apple", "banana", "kiwi", "fig", "grape", "pear", "melon"}; quicksort(arr, 0, arr.length - 1); System.out.println(Arrays.toString(arr)); } public static void quicksort(String[] arr, int low, int high) { if (low < high) { int pi = partition(arr, low, high); quicksort(arr, low, pi - 1); quicksort(arr, pi + 1, high); } } private static int partition(String[] arr, int low, int high) { String pivot = arr[high]; int i = (low - 1); for (int j = low; j < high; j++) { if (customComparator(arr[j], pivot) < 0) { i++; String temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } String temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } private static int customComparator(String a, String b) { int lengthCompare = Integer.compare(a.length(), b.length()); return lengthCompare != 0 ? lengthCompare : a.compareTo(b); } } ``` When I run this code, the output is not consistently sorted as expected. For example, if the input is `"apple", "fig", "kiwi", "pear"`, I sometimes get orderings like `[fig, kiwi, apple, pear]`, which is incorrect since both 'apple' and 'pear' are of length 5 and should be sorted alphabetically. I've verified that the custom comparator works independently, and I even tried using `Arrays.sort()` with the same comparator, which produces the correct results. Is there something specific about how I'm implementing the partition logic in the Quicksort that could lead to these inconsistencies? Any help on fixing this would be appreciated! For context: I'm using Java on Linux. What am I doing wrong?