on sunday, i was writing the bubble sort algorithm in java, to sort the contents of an array in ascending order.
it was part of a college assignment.
the next day, my practical instructor tests my program. first, he uses positive integers, and the bubble sort sorts them beautifully.
next, he enters negative values into the array.
and when he runs the bubble sort, it gives one helluva output!
Code: Select all
-3454 -4332 -7690 0 1232 4545
and when we sort the same array, with the same values using selection and insertion sort, it gives the right output.
Code: Select all
-7690 -4332 -3454 0 1232 4545
now, i need to find out why this is happening, and i've completely lost it.
i'm attaching the java code listing for the bubble sort method. if you guys don't mind, can you please, please take a peek and give me a clue as to what's wrong??
thanks!
Code: Select all
public void bubblesort()
{
int out, in;
for(out=nElems-1;out>1;out--)
{
for(in=0;in<out;in++)
{
if(a[in]>a[in+1])
{
double temp=a[in];
a[in]=a[in+1];
a[in+1]=temp;
}
}
}
}