2012-07-01 50 views
0

我试图在Java中实现QuickSort算法。但是每当我运行代码时,它都会给我一个StackOverFlowException的运行时异常。我似乎无法弄清楚为什么我的界限搞乱了。这是代码。堆栈溢出解决QuickSort算法的异常

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

感谢您的帮助! :)

+4

欢迎来到Stack Overflow!要求陌生人通过检查发现代码中的错误并不是富有成效的。您应该使用调试器或打印语句来识别(或至少隔离)问题,然后回来一个更具体的问题(一旦您将其缩小到10行[测试案例](http:///sscce.org))。 –

+3

那么,你有没有尝试过在每次递归中添加诊断来查找'l'和'r'的值? –

+0

我很好奇看到分区返回的值。方法名称,顺便说一下,应该是camelcase,并以小写字母开头。 –

回答

0

您应该查看此算法的源代码,因为您的分区方法与传统分区方法几乎没有相似之处。

你一定在尝试进行分区,所以你可能想看看维基百科上的这个in-place version,并尝试做那里描述的内容。

此外,一旦你得到你的分区工作,主轴应该就位,其索引可以跳过递归调用,你的递归没有做。