码迷,mamicode.com
首页 > 其他好文 > 详细

自考新教材-p352_2

时间:2020-02-06 11:01:08      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:for   pen   sort   space   ios   image   冒泡排序   运行   mamicode   

源程序:

用三种排序:冒泡排序,直接插入排序,直接选择排序

#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

标签:for   pen   sort   space   ios   image   冒泡排序   运行   mamicode   

原文地址:https://www.cnblogs.com/duanqibo/p/12267601.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!