gpt4 book ai didi

java - 我在 Java 中的快速排序算法出现问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:21:48 25 4
gpt4 key购买 nike

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;
}

大家好,我在学习快速排序算法的过程中遇到了一些困难。在上面的代码中,我尝试使用快速排序方法对 String 数组进行排序。出于某种原因,当我尝试运行该方法时,该方法不起作用,而且由于这对我来说是一个新主题,所以我无法弄清楚我需要修复什么。任何反馈将不胜感激。

最佳答案

我试过执行你的程序,建议将 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] + " ");

}
}
}

关于java - 我在 Java 中的快速排序算法出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29404954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com