自考新教材-p352_2

Posted duanqibo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自考新教材-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;
}

 

运行结果:

技术图片

 

以上是关于自考新教材-p352_2的主要内容,如果未能解决你的问题,请参考以下文章

自考新教材-p352_3

自考新教材-p352_3

自考新教材-p274_2

自考新教材-p272_2

自考新教材-p240_2

自考新教材-p279_2