zoukankan      html  css  js  c++  java
  • 作业3 简单的查找算法

    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

  • 相关阅读:
    Python获取秒级时间戳与毫秒级时间戳
    时间戳与时间类型转化(秒级时间戳)
    linux压缩和解压缩命令
    对于Python中@property的理解和使用
    探索性测试方法
    Linux 中 grep 命令的 12 个实践例子
    在 Linux 启动或重启时执行命令与脚本
    亲测的orabbix监控Oracle过程
    find 使用搜集
    Centos7.3-mysql5.7复制安装过程
  • 原文地址:https://www.cnblogs.com/Fanchile/p/12464918.html
Copyright © 2011-2022 走看看