JOIN
Get Time
forums   
Search | Watch Thread  |  My Post History  |  My Watches  |  User Settings
View: Flat (newest first)  | Threaded  | Tree
Previous Thread  |  Next Thread
Regarding bubble sort algorithm | Reply
I was just going through the bubble sort's code and there seems to be an issue there.

The loop indexes are:

for (int i = 0; i < data.Length; i++)
for (int j = 0; j < data.Length - 1; j++)


The inner loop would bubble the largest element to the end of the list instead of "bubbling" the smallest element to the top of the list. Then when we go to the outer loop, we increment i and hence the first element in the list (which is not the smallest element) would be left unchanged.

For example: consider the array 5 4 3 2 1

After 1st iteration, it would become: 4 3 2 1 5
Now i goes to 1 which is pointing to the element "3" in the array. "4" is never sorted ever again. Shouldn't the correct implementation be something like:

for (int i = 0; i < data.Length; i++)
for (int j = data.length; j > i + 1; j--)
if (data[j] < data[j - 1])
{
tmp = data[j];
data[j] = data[j - 1];
data[j - 1] = tmp;
}
}
}


Please correct me if I am wrong here, thanks.
Re: Regarding bubble sort algorithm (response to post by gaurav123) | Reply
It's probably good to have bugs in all published bubble sort implementations, so that nobody uses it, even as a placeholder for future code. :)
Re: Regarding bubble sort algorithm (response to post by gaurav123) | Reply
Don't you think you forgot to look at 'j'?
Re: Regarding bubble sort algorithm (response to post by visualage) | Reply
that's true, my bad. Somehow I just read j as being initialized to i instead of 0. thanks a lot for pointing it out :-)
RSS