为了加强自己的计算机思维和编程功底,会尝试使用底层语言来实现一下传统算法,目的加强基本功的同时督促自己坚持学习。
- 插入排序
插入排序的基本思想是:每步将一个待排序的记录,按其关键码值的大小插入前面已经排序的文件中适当位置上,直到全部插入完为止。
# include<iostream>
// 定义输入函数
template<typename type> void inputnumber(type *a, int length)
{
type input;
std::cout << "please enter numbers:" << std::endl;
for (int i = 0;i<length;i++)
{
std::cin >> input;
a[i] = input;
}
}
// 定义输出函数
template<typename type> void printnumber(type *a, int length)
{
for (int i = 0;i<length;i++)
std::cout << a[i] << " ";
std::cout << std::endl;
}
// 插入排序函数
template<typename type> void insertsort(type *a, int length)
{
int i, j;
type v;
for (i=1;i<length;i++)
{
v = a[i];
j = i - 1;
while ((j >=0) && (a[j]> v))
{
a[j+1] = a[j];
j--;
}
a[j+1] = v;
}
printnumber(a, length);
}
// 运行函数
template<typename type> void run(type *a, int length)
{
inputnumber(a, length);
std::cout << "show original array:" << std::endl;
printnumber(a, length);
std::cout << "show sorted array:" << std::endl;
insertsort(a, length);
}
// 主函数
int main()
{
int length = 10;
int a[10];
float b[10];
double c[10];
// 输入整型数组
run(a, length);
// 输入浮点型数组
run(b, length);
// 输入双精度型数组
run(c, length);
return 0;
}
运行结果:
整型
浮点型
- 双精度型