bubble sort

my following code is not running properly plz suggest a solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 #include <iostream>
using namespace std;
int main()
{
    int arr[10];
    int n;
    cout<<"Enter the number of elements of array"<<endl;
    cin>>n;
    cout<<"Enter the elements of array"<<endl;
    for(int i=0;i<n;i++)
    {
        cin>>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"<<endl;
    for(int i=0;i<=n-1;i++)
    {
        cout<<arr[i];
    }
}
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?
26
27
28
29
30
    cout<<"Elements after sorting are"<<endl;
    for(int i=0;i<=n-1;i++)
    {
        cout<<arr[i]<<" ";
    }

1
2
3
4
5
6
7
8
9
10
11
12
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:
1
2
3
4
5
6
 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.