Bubble sorting error

Hi!
I am trying to sort an array with Bubble shorting technique. it works fine until last value. when last value is to be sorted it converts last value in to 0 and sort it. any way to solve it.
Thanks
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int arr[10],i,j,temp;
for(i=0;i<=4;i++)
{
cout<<"Enter a number:";
cin>>arr[i];
}
cout<<"Orignal array is"<<endl;
for(i=0;i<=4;i++)
{
cout<<arr[i]<<"\t";
}
for(i=0;i<=4;i++)
{
for(j=0;j<=4;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
cout<<endl<<"Sorted array is"<<endl;
for(i=0;i<=4;i++)
{
cout<<arr[i]<<"\t";
}
getch();
return 0;
}
Last edited on
you are stepping out of bounds.
1
2
3
for(j=0;j<=4;j++)
{
   if(arr[j]>arr[j+1])
last iteration j=4, so you are doing if( arr[4]>arr[5] ) but you never initialised arr[5], it has garbage.
Topic archived. No new replies allowed.