I am making a simple program on Heap Sort. Please review my code, and let me know my error. It maybe that I am using the wrong approach. Thanks in advance.
The insert method take two arguments. Integer key is the element which I need to insert and Integer i is the index of the key which is in another array(ie Main class).
public static void main(String[] args) {
Integer arr[]={81,67,78,59,32,8,96};
Main a =new Main();
for(int i=0;i<arr.length;i++)
{
a.insert(arr[i], i);
}
public void insert(Integer key, Integer i) {
int head=0;
if(temp[head]==null)
{
temp[head]=key;
}
else
{
if(key>=temp[head]){
Integer j=(2*i)+2;
i=j;
insert(key, i);
}
else
{
Integer j=(2*i)+1;//Stackoverflow error is coming over here.
i=j;
insert(key,i);
}
}
}
似乎除了第一个元素以外,插入另一个元素将使您的方法永远保持自身调用,因为所有执行路径均导致再次调用该方法,但0处的元素为null时例外。
一旦temp [0]不为null,并且密钥大于或等于temp [0],您将遇到无限递归。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.