我是一名计算机科学专业的学生,我被分配修改一个给定的快速排序方法,该方法对整数进行排序,以便能够对字符串数组进行排序。我已经完成这项任务几个小时了,但我似乎无法弄清楚为什么我的代码不会对字符串数组进行排序。我遇到的唯一问题是该方法不会对数组进行排序,它只会输出一个看似没有模式的混乱数组。下面是我修改过的代码。非常感谢任何帮助查明我的代码中的错误或错误的帮助。
package lab6;
public class ObjectQuickSorter
{
public static void quickSort(String array[])
{
doQuickSort(array, 0, array.length - 1);
}
private static void doQuickSort(String array[], int start, int end)
{
int pivotPoint;
if (start < end)
{
// Get the pivot point.
pivotPoint = partition(array, start, end);
// Sort the first sublist.
doQuickSort(array, start, pivotPoint - 1);
// Sort the second sublist.
doQuickSort(array, pivotPoint + 1, end);
}
}
private static int partition(String array[], int start, int end)
{
String pivotValue; // To hold the pivot value
int endOfLeftList; // Last element in the left sublist.
int mid; // To hold the mid-point subscript
// Find the subscript of the middle element.
// This will be our pivot value.
mid = (start + end) / 2;
// Swap the middle element with the first element.
// This moves the pivot value to the start of
// the list.
swap(array, start, mid);
// Save the pivot value for comparisons.
pivotValue = array[start];
// For now, the end of the left sublist is
// the first element.
endOfLeftList = start;
// Scan the entire list and move any values that
// are less than the pivot value to the left
// sublist.
for (int scan = start + 1; scan <= end; scan++)
{
if (array[scan].compareTo(pivotValue) < 0)
{
endOfLeftList++;
swap(array, endOfLeftList, scan);
}
}
// Move the pivot value to end of the
// left sublist.
swap(array, start, endOfLeftList);
// Return the subscript of the pivot value.
return endOfLeftList;
}
private static void swap(String[] array, int a, int b)
{
String temp;
temp = array[a];
array[a] = array[b];
array[b] = temp;
}
}
这是用来测试方法的代码:
public static void main(String[] args)
{
//Creating an array of Strings
String[] arr = {"Computer", "Phone", "Dog", "Turtle" };
//Printing out the original array of Strings
System.out.println("Original order:");
for (String element : arr)
System.out.println(element + " ");
//Sorting the array of Strings
ObjectQuickSorter.quickSort(arr);
//Printing the sorted array
System.out.println("\nSorted order:");
for (String element : arr)
System.out.println(element + " ");
}