I have checked again and again for any problems in the code but can't figure out why my bubble sorting program is not giving correct output. Can you please help me identify?
#include <iostream.h>
#include <conio.h>
using namespace std;
main()
{
int number[10];
int temp=0;
int i=0;
cout<<"Please enter any ten numbers to sort one by one: "<<"\n";
for (i=0;i<10;i++)
{
cin>>number[i];
}
i=0;
for (i=0;i<10;i++)
{
if(number[i]>number[i+1])
{
temp=number[i+1];
number[i+1]=number[i];
number[i]=temp;
}
}
i=0;
cout<<"The sorted numbers are given below:"<<"\n";
for (i=0;i<10;i++)
{
cout<<number[i]<<"\n";
}
getch();
}
Edit: I have accepted what you all said that there must be an outer loop. But again I'm thinking on what I have written. I think the ONLY loop with the bubble condition should do the sorting. Here is what I'm thinking:
for (i=0;i<10;i++)
if(number[i]>number[i+1])
{
temp=number[i+1];
number[i+1]=number[i];
number[i]=temp;
}
}
Now I explain what I am thinking what this loop "should" do. It will first compare number[0] with number[1]. If the condition is satisfied it will do what is in IF statement's body. Then i will be incremented by 1(i++). Then on next iteration the values compared will be number[1] with number[2]. Then why it does not happen and the loop exits after only pass? In other words may be I'm trying to ask IF statement does not repeat itself in for loop? In my opinion it does. I'm very thankful for help and views, my question might be of small level but that is how I will progress. Thanks.
This is only the first pass of a Bubble Sort. You need to repeat your sort part until no sorting is performed during a pass.
number[i+1]
, which is an undefined behaviorHere is how you can fix your main loop:
bool again;
do {
again = false;
for (i=0;i<9;i++)
{ // ^-- Nine, not ten
if(number[i]>number[i+1])
{
temp=number[i+1];
number[i+1]=number[i];
number[i]=temp;
again = true;
}
}
} while (again);
its quite dangerous to have
int number[5];
and ask the user to enter 10 values ;-)
You are going out of bounds of the array. Make the loop run 5 times, not 10.
Secondly you are trying to sort the array in just one pass. Make nested loops. for complete sort. For Example if you have this array.
3 4 1 2 6
After one pass, as you are doing, it would look like this.
3 1 2 4 6
So this array is not completely sorted. Make two loops for complete sorting.
And make sure to run the loops till size - 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With