Java 数组快速排序中的堆栈溢出
有谁知道为什么我在以下代码中的快速排序上会出现堆栈溢出?:
private int[] concat( int[] less, int inxl, int pivot, int inxm, int[] more )
{
int[] concated = new int[ less.length ];
for( int inx = 0; inx < inxl; inx++ )
{
concated[ inx ] = less[ inx ];
}
concated[ inxl ] = pivot;
inxl++;
for( int inx = 0; inx < inxm; inx++ )
{
concated[ inxl ] = more[ inx ];
inxl++;
}
return concated;
}
private int[] quickSort( int[] array )
{
if( array.length <= 1 )
return array;
int[] less = new int[ array.length ];
int[] more = new int[ array.length ];
int inxl = 0, inxm = 0;
for( int inx = 1; inx < array.length; inx++ )
{
if( array[ inx ] < array[ 0 ] )
{
less[ inxl ] = array[ inx ];
inxl++;
}
else
{
more[ inxm ] = array[ inx ];
inxm++;
}
}
return concat( quickSort( less ), inxl, array[ 0 ], inxm, quickSort( more ) );
}
任何帮助将不胜感激。我正在为面试而复习,有点生疏,所以时间非常重要。预先感谢! :)
真挚地, 彼得。
Does anyone have any idea why I would be getting a stack overflow on my quicksort in the following code?:
private int[] concat( int[] less, int inxl, int pivot, int inxm, int[] more )
{
int[] concated = new int[ less.length ];
for( int inx = 0; inx < inxl; inx++ )
{
concated[ inx ] = less[ inx ];
}
concated[ inxl ] = pivot;
inxl++;
for( int inx = 0; inx < inxm; inx++ )
{
concated[ inxl ] = more[ inx ];
inxl++;
}
return concated;
}
private int[] quickSort( int[] array )
{
if( array.length <= 1 )
return array;
int[] less = new int[ array.length ];
int[] more = new int[ array.length ];
int inxl = 0, inxm = 0;
for( int inx = 1; inx < array.length; inx++ )
{
if( array[ inx ] < array[ 0 ] )
{
less[ inxl ] = array[ inx ];
inxl++;
}
else
{
more[ inxm ] = array[ inx ];
inxm++;
}
}
return concat( quickSort( less ), inxl, array[ 0 ], inxm, quickSort( more ) );
}
Any help would be greatly appreciated. I am revising for an interview and been a little rusty so time is of grave importance. Thanks upfront! :)
Sincerely,
Piotr.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
quickSort
方法的递归是错误的。它应该使用较小的数组(或使用其他一些变小的参数)来调用自身,而不是使用相同长度的数组。这就是为什么你会得到无休止的递归,它显示为 StackOverflowError 。Your
quickSort
method's recursion is wrong. It should call itself with smaller arrays (or with some other parameter which gets smaller), not with arrays of the same length. This is why you get an endless recursion, which shows up as aStackOverflowError
.我想知道你是否永远递归。在快速排序方法中,您在哪里缩小数组大小?您是否在数组大小上使用过 println 来首次查看它是否变小?
I wonder if you're recursing forever. Where do you shrink the array size within your quicksort method? Have you used println's on the array size to debut to see if it's getting smaller?