Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

c++ - bubble sort in descending order

int main()
{
    int a[7] = {4,33,11,8,12,123,2}, temp;

    for (int i = 7; i >= 0; i--)
    {
        for (int j = 7; j > 7 - i; j--)
        {
            if (a[j] > a[j - 1])
            {
                temp = a[j];
                a[j] = a[j - 1];
                a[j - 1] = temp;
            }
        }
    }

    for (int i = 0; i < 7; i++)
        cout << a[i] << " ";

}

Hey, I want to sort numbers for bubble descending sort, but I have a problem, my code works with (ai >= 0) and when I enter negative numbers wrong output is given. for example when i entered {4,33,-1,8,12,123,2}, output is

123 33 12 8 4 2 0
question from:https://stackoverflow.com/questions/65831093/bubble-sort-in-descending-order

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your program has undefined behavior because within the loops you are trying to access memory beyond the array.

That is in the inner loop

    for (int j = 7; j > 7 - i; j--)
    {
        if (a[j] > a[j - 1])
        {
            temp = a[j];
            a[j] = a[j - 1];
            a[j - 1] = temp;
        }
    }

the initial value of the variable j is 7 and you are using this value to access elements of the array in the if statement.

In fact in the first iteration of the loop you have

        if (a[7] > a[6])

but 7 is not a valid index to access elements of the array.

It will be simpler to write the loops with indices starting with 0. All what you will need is to change the comparison expression in the if statement.

Nevertheless your updated program can look for example the following way

#include <iostream>

int main() 
{
    int a[] = { 4, 33, -1, 8, 12, 123, 2 };
    const size_t N = sizeof( a ) / sizeof( *a );
        
    for ( const auto &item : a ) std::cout << item << ' ';
    std::cout << '
';

    for ( size_t i = N; i != 0; --i )
    {
        for ( size_t j = N; --j != N - i;   )
        {
            if ( a[j-1] < a[j] )
            {
                int tmp = a[j];
                a[j] = a[j-1];
                a[j-1] = tmp;
            }
        }
    }
        
    for ( const auto &item : a ) std::cout << item << ' ';
    std::cout << '
';
    
    return 0;
}

The program output is

4 33 -1 8 12 123 2 
123 33 12 8 4 2 -1 

A more flexible approach is to write a separate template function which excepts two iterators of the category of the forward iterator.

In this case to sort an array in the descending order it will be enough to call the function with reverse iterators.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...