### bubble sort

my following code is not running properly plz suggest a solution

 ``12345678910111213141516171819202122232425262728293031`` `````` #include using namespace std; int main() { int arr[10]; int n; cout<<"Enter the number of elements of array"<>n; cout<<"Enter the elements of array"<>arr[i]; } for(int i=0;i<=n-1;i++) { for(int j=0;j<=n-1-i;j++) { if(arr[j]>arr[j+1]) { int temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } cout<<"Elements after sorting are"<
Last edited on
It did work for me, what's wrong ?
More details than 'not running correctly' would be good.
I see no error in your bubble sort either... did you fix it with your edit?

Perhaps this?
 ``2627282930`` `````` cout<<"Elements after sorting are"<

 ``123456789101112`` ``````int main() { const int MAXSZ = 10 ; int arr[MAXSZ] ; int n; cout << "Enter the number of elements of array " ; cin >> n ; if( n > MAXSZ ) n = MAXSZ ; // *** added: limit n to size of array // ... ``````

Though this is fine: `for(int i=0;i<=n-1;i++)` (when n is a signed integer)

Prefer the canonical form that is commonly seen, one that is familiar to programmers.
`for( int i = 0 ; i<n ; ++i ) `
for eg...if i enter 5 elements..say..8 1 4 2 3...elements that i get after sorting are 0 1 2 3 4...from wheredoes this 0 cum from n why isnt 8 displayed?
@Mishu
Hi, I think you made a mistake here:
 ``123456`` `````` for(int i=0;i<=n-1;i++) { for(int j=0;j<=n-1-i;j++) { if(arr[j]>arr[j+1]) // here is the problem {``````

Actually this is a common overflow error, when i=0, then j could reach n-1-i which equals to n-1, but in the next line we compared arr[j] with arr[j+1], but j+1=(n-1)+1=n, this is a overflow since arr doesn't have this element.

Boundaries should be treated very carefully, it could cause some kind of fancy problems.

@Yueeng +1. Thank you!
thnx a lot!
Topic archived. No new replies allowed.