自考新教材-p352_2
源程序:
用三种排序:冒泡排序,直接插入排序,直接选择排序
#include <iostream>
#define N 5
using namespace std;
template <typename T>
//冒泡排序
/*
void bubble_sort(T a[], int n)
{
int i, j;
T temp;
for (i = 0; i < n; i++)
{
for (j = 0; j < n - i - 1; j++)
{
if (a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
*/
//直接插入排序
/*
void straight_sort(T a[], int n)
{
int i, j;
T temp;
for (i = 1; i < n; i++)
{
temp = a[i];
j = i - 1;
while (temp < a[j])
{
a[j + 1] = a[j];
j--;
}
a[j + 1] = temp;
}
}
*/
//直接选择排序
void select_sort(T a[], int n)
{
int min, i, j;
T temp;
for (i = 0; i <= n - 1; i++)
{
min = i;
for (j = i + 1; j < n; j++)
if (a[j] < a[min])
min = j;
if (min != i)
{
temp = a[min];
a[min] = a[i];
a[i] = temp;
}
}
}
int main()
{
int num[N] = { 5,2,8,1,4 }, i;
double num1[N] = {5.5,2.2,8.8,1.1,4.4};
char num2[N] = {'m','p','b','w','h'};
/*
bubble_sort(num, N);
for (i = 0; i < N; i++)
cout << num[i] << " ";
cout << endl;
bubble_sort(num1, N);
for (i = 0; i < N; i++)
cout << num1[i] << " ";
*/
/*
straight_sort(num, N);
for (i = 0; i < N; i++)
cout << num[i] << " ";
cout << endl;
straight_sort(num1, N);
for (i = 0; i < N; i++)
cout << num1[i] << " ";
*/
select_sort(num, N);
for (i = 0; i < N; i++)
cout << num[i] << " ";
cout << endl;
select_sort(num1, N);
for (i = 0; i < N; i++)
cout << num1[i] << " ";
cout << endl;
select_sort(num2, N);
for (i = 0; i < N; i++)
cout << num2[i] << " ";
system("pause");
return 1;
}
运行结果: