C语言-顺序查找和二分查找

本文详细介绍了C语言中两种常见的查找算法——顺序查找和二分查找。顺序查找适用于未排序的数组,而二分查找则需要先对数组进行排序,且在去重的情况下仍能有效工作。
摘要由CSDN通过智能技术生成

顺序查找

#include <stdio.h>
typedef void (*call_back)(int);
void printIndex(int index)
{
   printf("%d\t",index);
}
int linear(int *array, int length, int target, call_back ptr)
{
   int count = 0;
   for (int i = 0; i < length; i++)
   {
       if(array[i] == target)
       {
           ptr(i);
           count++;
       }
   }
   return count;
}
int main()
{
   int linear_array[20] = {234, 12, 78, 980, 345, 2, 17, 78, 643, 108, 23, 78, 256, 90, 379, 23, 98, 100, 21, 8};
   int target = 78;
   int count = linear(linear_array, sizeof(linear_array)/sizeof(int), target, printIndex);
   if(count == 0)
   {
       printf(" \nThere is no num in the array matching the target. \n");
   }
   else
   {
       printf("\nThere are %d nums matching the target num and the positions are above", count);
   }
}


2   7   11 
There are 3 nums matching the target num and the positions are above
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值