public static String[] quickSort(String[] givenArray, int left, int right)
{
int l = left;
int r = right;
//used to temporarily hold values for swapping process
String temp;
//arbitrarily picking a pivot point since I know the how much the array holds...
String pivot = givenArray[33];
while (l<=r)
{
while (givenArray[l].compareTo(pivot) < 0)
{
l++;
}
while (givenArray[r].compareTo(pivot) > 0)
{
r--;
}
if (l <= r)
{
temp = givenArray[l];
givenArray[l] = givenArray[r];
givenArray[r] = temp;
l++;
r--;
}
}
if (left < r)
{
quickSort(givenArray, left, r);
}
if (l < right)
{
quickSort(givenArray, l, right);
}
return givenArray;
}
大家好,所以我在学习快速排序算法的过程中遇到了一些困难。在上面的代码中,我尝试使用quicksort方法对String数组进行排序。出于某种原因,当我尝试运行该方法时,该方法不起作用,并且由于它对我来说是一个新主题,因此我无法确定需要修复的内容。任何反馈将不胜感激。
答案 0 :(得分:0)
我尝试执行你的程序,并建议一个小的改变String pivot = givenArray [33]应该改为String pivot = givenArray [right];
please find the below example:
public class Triangle{
public static String[] quickSort(String[] givenArray, int left, int right)
{
int l = left;
int r = right;
//used to temporarily hold values for swapping process
String temp;
//arbitrarily picking a pivot point since I know the how much the array holds...
String pivot = givenArray[right];
while (l<=r)
{
while (givenArray[l].compareTo(pivot) < 0)
{
l++;
}
while (givenArray[r].compareTo(pivot) > 0)
{
r--;
}
if (l <= r)
{
temp = givenArray[l];
givenArray[l] = givenArray[r];
givenArray[r] = temp;
l++;
r--;
}
}
if (left < r)
{
quickSort(givenArray, left, r);
}
if (l < right)
{
quickSort(givenArray, l, right);
}
return givenArray;
}
public static void main (String arg[]){
String[] givenArray = new String[]{"X","E","C","A"};
printArray(quickSort(givenArray,0,givenArray.length-1));
}
public static void printArray(String[] sorted){
for (int i = 0; i < sorted.length; i++) {
System.out.print(sorted[i] + " ");
}
}
}