1. Member
Join Date
Nov 2007
Posts
2
Rep Power
0

## Heap Sorting

I m facing a error in this program...can any body help me in this regard.
im pasting my code below.
Its throwing a error message
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9

Java Code:
```class Heapsort
{
public static void main (String args[])
{
int array[]={55,40,80,65,71};
int i; int j; int tmp;

for(i=array.length/2-1; i>=0; i--)
{
j=2*i+1;
while (j<array.length)
{
if(j+1<array.length)
if (array[j+1]>array[j]) j++;

if(array[i]>=array[j])
{
tmp=array[i];
array[i]=array[j];
array[j]=tmp;
}
i=j; j=2*i+1;
}

while(array.length>1)
{
array[i]--;
tmp=array[i];
array[i]=array[j];
array[j]=tmp;
if(j+1<array.length)
if (array[j+1]>array[j]) j++;

if(array[i]>=array[j])
{
tmp=array[i];
array[i]=array[j];
array[j]=tmp;
}
i=j; j=2*i+1;
}

}
System.out.print(" " + array);
}
}```
Last edited by JavaBean; 11-13-2007 at 12:14 PM. Reason: Please place your codes inside [code] tag next time!

2. On the first iteration of the for loop, i=1 and j=3. During the while loop, j is incremented. At the end of the while loop, i=j (which is now 4) and j becomes 2*i+1 (9). In the second while loop, the statement array[i]=array[j] causes the exception because j is 9. I could be wrong though.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•