先看程序:
public class DivisionSort
{
public static int[] getSort(int[] test)
{
//先取出一个中间的值
int middle=test.length/2;
if(middle>0)
{
int i=0;
int j=0;
int temp=0;
//算出比中间值小的值,组成数组
for(i=0;i<test.length;i++)
{
if(test[i]<=test[middle])
{
j++;
}
}
i=j;
j=test.length-i;
int[] front=new int[i];
int[] back=new int[j]; //把数据分给两个数组
for(temp=0;temp<test.length;temp++)
{
if(test[temp]<=test[middle])
{
i--;
front[i]=test[temp];
}else
{
j--;
back[j]=test[temp];
}
}
//递归排序,就是这里出了问题!
front=getSort(front);
back=getSort(back);
//组合为一个数组
for(temp=0;temp<test.length;temp++)
{
if(temp<front.length)
{
test[temp]=front[temp];
}else
{
test[temp]=back[temp-front.length];
}
}
//返回
return test;
}else
{
return test;
}
}
public static void main(String arg[])
{
int x;
int[] temp=new int[arg.length];
for(x=0;x<arg.length;x++)
{
temp[x]=Integer.parseInt(arg[x]);
}
temp=getSort(temp);
for(x=0;x<arg.length;x++)
{
System.out.println(new Integer(temp[x]).toString());
} }
}
程序运行后,数一多就堆栈溢出,想知道怎么样改动就好了。
public class DivisionSort
{
public static int[] getSort(int[] test)
{
//先取出一个中间的值
int middle=test.length/2;
if(middle>0)
{
int i=0;
int j=0;
int temp=0;
//算出比中间值小的值,组成数组
for(i=0;i<test.length;i++)
{
if(test[i]<=test[middle])
{
j++;
}
}
i=j;
j=test.length-i;
int[] front=new int[i];
int[] back=new int[j]; //把数据分给两个数组
for(temp=0;temp<test.length;temp++)
{
if(test[temp]<=test[middle])
{
i--;
front[i]=test[temp];
}else
{
j--;
back[j]=test[temp];
}
}
//递归排序,就是这里出了问题!
front=getSort(front);
back=getSort(back);
//组合为一个数组
for(temp=0;temp<test.length;temp++)
{
if(temp<front.length)
{
test[temp]=front[temp];
}else
{
test[temp]=back[temp-front.length];
}
}
//返回
return test;
}else
{
return test;
}
}
public static void main(String arg[])
{
int x;
int[] temp=new int[arg.length];
for(x=0;x<arg.length;x++)
{
temp[x]=Integer.parseInt(arg[x]);
}
temp=getSort(temp);
for(x=0;x<arg.length;x++)
{
System.out.println(new Integer(temp[x]).toString());
} }
}
程序运行后,数一多就堆栈溢出,想知道怎么样改动就好了。
解决方案 »
- 设计一个百亿计算器的思路?
- java Class.forName 创建多个实例 问题 帮个忙...急
- 请教一个jfreechart的问题
- main方法中的变量算不算局部变量?
- JDK 1.6 Date 类中年份超过9999时,为何只显示最后的三个数字??
- 求一个两数组里的元素是否相同的比较算法,在线等达人,谢谢啦~~
- 请问复制(CTRL+C)是怎么实现的
- 高手来帮我看看出了什么问题,解决马上结帖。
- servlet的context 中getInitParameterNames使用不了,请帮忙!
- 在线帮助
- 请教个JTextArea的问题,想做一个类似QQ输入信息的地方,可以粘贴图片进去
- 哪有下载java资料的ftp啊
出错原因是出现了死循环: i=j;
j=test.length-i;
int[] front=new int[i];
int[] back=new int[j];
if(i==0||j==0)return test;//添加上这行用于跳出
//把数据分给两个数组
建议重新理一下逻辑,二分法没必要这么复杂的