我正在尝试用 Java 实现快速排序算法。但是每当我运行代码时,它都会给我一个 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;
}
}