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.
number[i+1], which is an undefined behaviorHere is how you can fix your main loop: