简体   繁体   中英

Bubble sort in c++ (asc)

I've seen a tutorial regarding to bubble sort an arrays.

Here's the code that was used:

    int main()
    {
        int numbers[5];
    int asc;

    //input 5 integers
    cout << "Enter 5 Numbers : \n";
    for (int i = 0; i < 5; ++i) {
        cin >> numbers[i];
    }

    for (int i = 0; i < 5; ++i)   //  outer loop
    {
        for (int a = i + 1; a < 5; ++a) // inner loop
        {
            if (numbers[i] > numbers[a]) 
            {
                asc = numbers[i];
                numbers[i] = numbers[a]; // swapping
                numbers[a] = asc;
            }
        }
    }
    cout << endl << "Ascending Order : ";
    for (int i = 0; i < 5; ++i)
    {
        cout << numbers[i] << " ";
    }
    return 0;
}

I trying to understand each lines but I'm stuck in the outer loop, inner loop and the SWAPPING part, I got little bit confused on that part.

Any help? Thanks in advance!

Let the inputs be 5, 1, 4, 2, 8.

Since 5 > 1, (number[i] > number[i]+1)

You will need a variable to temporary store the value of number[i] before you perform the swapping and in this case, your variable is asc.

When asc is storing the value of number[i], the value of number[i+1] will replace the original value of number[i] and the value of asc will replace the value of number[i+1]. Hence, the swap in values of both the numbers are completed.

Multiple rounds of bubble sorts are required to completely sort the array. Below example is the visual representation of how bubble sort algorithm works.

First round of Bubble Sort:

( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.

( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4

( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2

( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.

Second round of Bubble Sort:

( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )

( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2

( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM