1:气泡法排序
//
用气泡法为n个数排序(从大到小)
#include < iostream >
using namespace std;
#define N 5
int main ()
{
int a[N] = { 0 };
for ( int i = 0 ;i < N;i ++ )
{
cin >> a[i];
}
for ( int j = 0 ;j < N - 1 ;j ++ ) // 交换轮数
for ( int i = 0 ;i < N - j - 1 ;i ++ ) // N-j次两个相邻数组元素的比较
{
int temp;
if (a[i] < a[i + 1 ])
{
temp = a[i];
a[i] = a[i + 1 ];
a[i + 1 ] = temp;
}
}
for ( int i = 0 ;i < N;i ++ ) // 输出数组
{
cout << a[i] << ' ' ;
}
cout << endl;
return 0 ;
}
#include < iostream >
using namespace std;
#define N 5
int main ()
{
int a[N] = { 0 };
for ( int i = 0 ;i < N;i ++ )
{
cin >> a[i];
}
for ( int j = 0 ;j < N - 1 ;j ++ ) // 交换轮数
for ( int i = 0 ;i < N - j - 1 ;i ++ ) // N-j次两个相邻数组元素的比较
{
int temp;
if (a[i] < a[i + 1 ])
{
temp = a[i];
a[i] = a[i + 1 ];
a[i + 1 ] = temp;
}
}
for ( int i = 0 ;i < N;i ++ ) // 输出数组
{
cout << a[i] << ' ' ;
}
cout << endl;
return 0 ;
}
2:改进的冒泡排序
//
改进的冒泡排序法
// 当是9,8,7,5,6只要排序一次,开始的方法就会做很多重复的工作了
#include < iostream >
using namespace std;
#define N 5
int main ()
{
int a[N] = { 0 };
for ( int i = 0 ;i < N;i ++ )
{
cin >> a[i];
}
int end = 0 ;
for ( int j = 0 ;j < N - 1 &&! end;j ++ ) // 交换轮数
{
end = 1 ; // end=1交换
for ( int i = 0 ;i < N - j - 1 ;i ++ ) // N-j次两个相邻数组元素的比较
{
int temp;
if (a[i] < a[i + 1 ])
{
temp = a[i];
a[i] = a[i + 1 ];
a[i + 1 ] = temp;
end = 0 ;
}
}
}
for ( int i = 0 ;i < N;i ++ ) // 输出数组
{
cout << a[i] << ' ' ;
}
cout << endl;
return 0 ;
}
// 当是9,8,7,5,6只要排序一次,开始的方法就会做很多重复的工作了
#include < iostream >
using namespace std;
#define N 5
int main ()
{
int a[N] = { 0 };
for ( int i = 0 ;i < N;i ++ )
{
cin >> a[i];
}
int end = 0 ;
for ( int j = 0 ;j < N - 1 &&! end;j ++ ) // 交换轮数
{
end = 1 ; // end=1交换
for ( int i = 0 ;i < N - j - 1 ;i ++ ) // N-j次两个相邻数组元素的比较
{
int temp;
if (a[i] < a[i + 1 ])
{
temp = a[i];
a[i] = a[i + 1 ];
a[i + 1 ] = temp;
end = 0 ;
}
}
}
for ( int i = 0 ;i < N;i ++ ) // 输出数组
{
cout << a[i] << ' ' ;
}
cout << endl;
return 0 ;
}
3:选择法排序
//
选择法排序(从小到大)
#include < iostream >
using namespace std;
#define N 5
int main ()
{
int a[N] = { 0 };
for ( int i = 0 ;i < N;i ++ )
{
cin >> a[i];
}
for ( int i = 0 ;i < N;i ++ )
{
int p = i;
for ( int j = i;j < N - 1 ;j ++ )
{
int temp;
if (a[p] > a[j + 1 ])
{
temp = a[p];
a[p] = a[j + 1 ];
a[j + 1 ] = temp;
}
}
}
for ( int i = 0 ;i < N;i ++ )
{
cout << a[i] << ' ' ;
}
cout << endl;
return 0 ;
}
#include < iostream >
using namespace std;
#define N 5
int main ()
{
int a[N] = { 0 };
for ( int i = 0 ;i < N;i ++ )
{
cin >> a[i];
}
for ( int i = 0 ;i < N;i ++ )
{
int p = i;
for ( int j = i;j < N - 1 ;j ++ )
{
int temp;
if (a[p] > a[j + 1 ])
{
temp = a[p];
a[p] = a[j + 1 ];
a[j + 1 ] = temp;
}
}
}
for ( int i = 0 ;i < N;i ++ )
{
cout << a[i] << ' ' ;
}
cout << endl;
return 0 ;
}