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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…