滴水2.4 排序 查找 模板
1.冒泡排序代码
点击查看代码
template<class T>
void qt(T al,int slong)
{
//// 4 1 5 6 7 8
int k = 0;
for (int k = 0; k < slong - 1; k++)
{
for (int i = 0; i < slong - 1-k; i++)
{
if (al[i] > al[i + 1])
{
//4 1
int temp = al[i];
al[i] = al[i + 1];
al[i + 1] = temp;
//1 4
}
}
}
}
2.折半查找
点击查看代码
/*
int arr[8] = {1,3,5,7,8,9,42,56};
*/
int zb(int* arr, int size,int nelemrnt)
{
int Begin = 0, End = size - 1, Index;
while (Begin <= End)
{
//中间数字
Index = (Begin + End) / 2;
printf("下标:%d\n", Index);
if (nelemrnt > arr[Index])
{
Begin = Index + 1;
}
else if (nelemrnt < arr[Index])
{
End = Index - 1;
}
else
{
return Index;
}
}
return 0;
}
如果我们需要对其他类型比较,难道还需要再写代码吗 这里我们用到模板
template< classT>
这里面的calss t可以代替任意符号
模板是代码的复制
作业 1.交换任意类型的值
点击查看代码
template<class N, class m ,class T>
void swap( N a,m b,T t)
{
t = a;
a = b;
b = t;
printf("a:%d------b:%d", a, b);
}
int main()
{
int a = 4;
char b = 3;
swap(a,b,1);
return 0;
}
计算机并不知怎么比较大小
本文来自博客园,作者:逆向狗,转载请注明原文链接:https://www.cnblogs.com/Agtw/p/17092208.html