Bubble sort

//Bubble sort(COMPILED N EXECUTED ON BORLAND C++)
#include <iostream.h>
#include <conio.h>
void main()
{
int a[5];
char v;
do{
cout<<"ENTER 5 VALUES:"<<"\n";

for(int i=0;i<5;i=i+1)
cin>>a[i];

int temp=0;

for(int r=0;r<5;r++)
{
for(int i=0;i<5;i++)
{

if(a[i]>a[i+1])
{
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}

cout<<"SORTED NUMBERS"<<'\n';
cout<<"============"<<'\n';

for(int j=0;j<5;j++)
{getch(); //just for tracking output
cout<<a[j]<<"\n";}

cout<<"wanna conntinue???\n"<<"Press Y to continue"<<"\n";
cin>>v;

}while(v=='y');
getch();
}

OUTPUT:
o/p:
ENTER 5 VALUES:
9
7
5
6
8
SORTED NUMBERS
============
1 // <-- From where this 1 came??
5
6
7
8
wanna conntinue???
Press Y to continue
y
ENTER 5 VALUES:
9
7
5
6
8
SORTED NUMBERS
============
5 // 1 is coming for the 1st time only.
6 //From 2nd itteration of do while, sorting is done properly.
7 // Pls. tell me wats wrong with this program..
8
9
wanna conntinue???
Press Y to continue
Last edited on
I don't see the problem. Maybe there's something odd about the compiler.
I'd recommend either http://www.codeblocks.org/ or http://orwelldevcpp.blogspot.co.uk/ as a more up-to-date IDE and compiler.
1
2
3
4
5
6
7
8
9
for(int i=0;i<5;i++)
{
   if(a[i]>a[i+1])
  {
  temp=a[i];
  a[i]=a[i+1];
  a[i+1]=temp;
  }
}

a[i+1] on the last run is always out of bounds
Suprised this works on the 2nd run.
@ Chervil..
Thanx dude...
Its runing properly on code block...
:)
Last edited on
@ noobletplusplus:
Ya u r ryt....
May b coz c++ dnt deal with array bound check and also due to some garbage value at a[5], which was greater than my inputs..
I tried for some random inputs, its also showing some unexpected outputs...
on CODE BLOCK..

thnx for ur reply...
it helped me a lot!!!!
Yes, noobletplusplus is correct.
Topic archived. No new replies allowed.