[英]Stack overflow Exception in solving QuickSort algorithm
我正在嘗試在Java中實現QuickSort算法。 但是,每當我運行代碼時,它就會為我提供StackOverFlowException的運行時異常。 我似乎無法弄清楚為什么我的界限混亂了。 這是代碼。
import java.util.Scanner;
class QuickSortOne
{
public static void main(String args[])
{
int a[], n;
Scanner sn = new Scanner(System.in);
n = sn.nextInt();
a = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = sn.nextInt();
}
QuickSort(a, 0, n-1);
for (int i = 0; i < n; i++)
System.out.println(a[i] + " ");
}
public static void QuickSort(int a[], int l, int r)
{
if (l < r) //Checking for Base Case
{
int p = Partition(a, l, r);
QuickSort(a, l, p);
QuickSort(a, p+1, r);
}
}
public static int Partition(int a[], int l, int r)
{
int p = a[l];
int i = l+1;
for (int j = l+1; j <= r; j++)
if (a[j] < p)
{
int temp = a[j];
a[j] = p;
p = temp;
i++;
}
int temp = a[i-1];
a[i-1] = p;
p = temp;
return i;
}
}
您應該查看此算法的源代碼,因為您的分區方法與傳統的分區方法幾乎沒有相似之處。
您肯定要嘗試在適當位置進行分區,因此您可能希望在Wikipedia上查看其就地版本 ,並嘗試執行此處描述的操作。
此外,一旦分區開始工作,樞軸就應該就位,並且可以在遞歸調用中跳過其索引,而遞歸不會這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.