zoukankan      html  css  js  c++  java
  • 基本的查找算法

    基本的查找算法有:顺序查找,二分查找,

    顺序查找很简答,就是遍历数组的每一个元素,通过与待查找到数进行比较来实现,一个for循环即可搞定。

    顺序查找不需要对数组进行排序,缺点是执行效率低,耗时,因为要遍历。

    二分查找是一个提高查找效率的方法,前提是数组有序,如果拿到一个无需的数组,首先要用排序算法(冒泡、选择、插入)来排序。

    二分查找的利用的是二分法,即将数组有一分为二,一半一半的缩小对比范围。

    二分法代码实现:

    class Test
    {
       public static void Main()
       {
           int[] number=new int[]{11,22,33,44,55,66,77,88,99};
           int  sValue=33;
           int index;
           index=Dichotomy(number,sValue);
           Console.WriteLine("{0}",  index);
        }
    
       public static int  Dichotomy(int[] num,int sValue)
      {  
            int upper=num.Length()-1;
             int lower=0;
           int mid= (upper+lower)/2;
           while( lower<=upper)
          {
                if(num[mid]==sValue)
               { 
                     return  mid;  //存在返回下标
                }
                  if(num[mid]>sValue)
                { 
                    upper=mid-1;
                }
                   if(num[mid]<sValue)
              {
                     lower=mid+1;
              }
            return -1;//不存在返回-1
           }

     public static int  Rdichotomy(int[] num,int sValue,int lower,int upper)//递归法实现
      {  
           
    if(lower>upper)
    {
    return -1;
    } else
    {
               if(num[mid]==sValue)
               { 
                     return  mid;  //存在返回下标
                }
               else  if(num[mid]>sValue)
                {
                    int upper=num.Length()-1;
                    int lower=0;
                    int mid= (upper+lower)/2;
    int[] num2=new int[]{upper-mid+1};
    for(int i=0;i<upper-mid+1;i++)
    {
                           num2[i]=num[lower+1+i];
    }
                    dichotomy(int[] num2,int sValue,int lower+1,int upeer);
                    )
                  else  if(num[mid]<sValue)
                 {
                    int upper=num.Length()-1;
                    int lower=0;
                    int mid= (upper+lower)/2;
    int[] num2=new int[]{upper-mid+1};
    for(int i=0;i<upper-mid+1;i++)
    {
                           num2[i]=num[i];
    }
                      dichotomy(int[] num2,int sValue,int lower+1,int upeer);
                    } 

    }
    }
  • 相关阅读:
    Elasticsearch轻量搜索与分析
    Elasticsearch文档详解
    Elasticsearch基本概念
    Elasticsearch集群健康
    Elasticsearch搜索与分析
    Redis 面试题 记录
    Redis集群 详解
    从根上理解高性能、高并发(六):通俗易懂,高性能服务器到底是如何实现的
    昔日移动端IM明星 “米聊” 即将停止服务
    从根上理解高性能、高并发(五):深入操作系统,理解高并发中的协程
  • 原文地址:https://www.cnblogs.com/lyjbk/p/11396348.html
Copyright © 2011-2022 走看看