1.     问题

写出两种检索算法:在一个排好序的数组T[1..n]中查找x,如果x在T中,输出x在T的下标j;如果x不在T中,输出j=0.按实验模板编写,“分析”部分仅给出复杂度结果即可。

2.     解析

主要实现两种算法,顺序查找和二分查找。顺序查找就是在数组中一个一个的查找,并判断是否符合要求。二分查找每次都去查找中间的值,并根据查找到的值来判断下次查找的区间。

3.     设计

顺序查找

       for(int i = 0;i < n;i++)

              if(number == data[i])

              {

                     printf("the index of the number you search is %d",i);

                     return i;

              }

      

       printf("the number you search doesn't exist");     

       return -1;

二分查找

int low,high,mid;

       low = 0;

       high = n-1;

       while(low < high)

       {

              mid = (low+high)/2;

              if(data[mid] == number)

              {

                     printf("the index of the number you search is %d",mid);

                     return mid;

              }

              else if(data[mid] < number)

                     low = mid +1;

              else if(data[mid] > number)

                     high = mid -1;

       }

       printf("the number you search doesn't exist'");

       return -1;

4.     分析

针对顺序查找,最多的查找次数为数组的长度n,因此事件复杂度为O(|n|),针对二分查找,最多的查找次数为log2n,因此时间复杂度为O(|log2n|)

5.     源码

https://github.com/fanchile/Algorithm

posted on 2020-03-11 19:45  饭吃了  阅读(138)  评论(0编辑  收藏  举报