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
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 << '\n';
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 << '\n';
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.