# Array sort

• 10-11-2008
freddyvorhees
Array sort
It sorts an array, max size of array is 1024 - the max size is given by our teacher.

Code:

```#include <iostream> using namespace std; int main() {         int a[1024], n, x, i, j;         cin >> n;         for ( i = 0; i < n; i++ )         {                 cin >> x;                 a[i] = x;         }         for ( i = 0; i < n; i++ )         {                 for ( j = 0; i+j+1 != n; j++ )                 {                         if ( a[i] > a[i+j+1] )                         {                                 x = a[i];                                 a[i] = a[i+j+1];                                 a[i+j+1] = x;                         }                 }         }         for ( i = 0; i < n; i++ )                 cout << a[i] <<" "; }```
I tried it and I haven't got any problem yet. Is/Will there be a problem with my code.

It's a bubble sort right?
• 10-11-2008
anon
There will be a problem if anyone chooses to input more than 1024 numbers. You might need a sanity check.

I'm not sure if it is exactly bubble-sort (which as far as I know should always compare two consecutive items: e.g j and j - 1.

But it looks like the index calculation in the inner loop could be simplified:
Code:

`for ( j = i + 1; j != n; j++ )`
and now just use j instead of i + j + 1 (since i + 1 is a constant in the inner loop).
• 10-11-2008
freddyvorhees
I think its okay the max is given by our teacher, that's what hes asking for.

I changed my code to this
Quote:

for ( j = i + 1; j != n; j++ )
So I guess there's nothing wrong anymore, right?
• 10-11-2008
dwks
Well, you might want to use better variable names. Even something like "temp", for example, would be better than "x".

I see you're re-using the variable x. I would try to avoid doing that if I were you.

Hopefully you also changed the code inside the inner for loop as well . . . .
• 10-11-2008
iMalc
As hinted, it's not Bubble Sort. Bubble Sort is stable because it compares adjacent items only. This doesn't do that.
It will certainly sort though and it's what I call Simple Sort, but if you need to have written Bubble Sort, then you have not done so.