zoukankan      html  css  js  c++  java
  • 【100题】第四十八题 移位数组的二分查找

    一,题目

            一个数组是由一个递减数列左移若干位形成的,比如{432165}是由{654321}左移两位形成的,在这种数组中查找某一个数。


    二,分析

            1)在此序列不断二分的过程中,由于原序列是一个递减序列经过旋转得到的,将它从任何位置分开,都会得到两个序列,

                                   其中一个是递减序列

                                   另一个可以通过一个递减序列通过旋转得到。

            2)这样在不断地二分查找时,我们处理的序列子片段要么就是一个旋转后递减序列,要么就是一个纯递减序列,

            3)无论是前者还是后者,在继续分成两个片段时,至少有一个纯递减序列(可能两个都是,如果之前的序列片段就是纯递减序列的话)。

            4)这样我们可以保证能找到一个片段是纯递减序列(if(data[i]>=data[j]))

            5)然后判断我们要找的数是否在这个片段中(这是很直观的,if(data[i]<=num&&num<=data[j])),如果在则继续在此片段中查找,否则说明在另一个序列中,则递归在其中查找

    三,源码

    #include<iostream>
    using namespace std;
    int bisearch(int a[],int left,int right,int num)
    {
     if(a==NULL||right<0)  
            return -1;  
    
        if(left==right)//还剩下一个值的时候 
        {  
            if(a[left]==num)  
                return left;  
            else  
                return -1;  
        }     
    
       //int mid=(left+right)/2;
       int mid=left+(right-left)/2;
       
       if(a[mid]==num)
           return mid;
           
       if(a[mid]<=a[left])//左侧纯递减 
       {
           if(num>a[mid]&&num<=a[left]) //左侧 
                return bisearch(a,left,mid-1,num);
           else
               return bisearch(a,mid+1,right,num);
       }
       else    //右侧纯递减 
       {
          if(num>=a[right]&&num<a[mid]) //右侧 
          		return bisearch(a,mid+1,right,num);
      	  else
         		return bisearch(a,left,mid-1,num);
       }
    }
    int main()
    {
     int a[100]={4,3,2,1,6,5};
        cout<<bisearch(a,0,5,6)<<endl;
     return 0;
    }
    
    
    


     


     

  • 相关阅读:
    Vue GET xxxx/sockjs-node/info?t=1573626343344 net::ERR_CONNECTION
    NavigationDuplicated Navigating to current location (“/XXX”) is not allowed
    node-sass报错(Node Sass could not find a binding for your current environment)
    DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead
    VSCODE 中.art文件识别为html文件
    gulp4.0构建任务
    gulp报错The following tasks did not complete
    setTimeout()
    格式化日期
    作业1.3
  • 原文地址:https://www.cnblogs.com/secbook/p/2654959.html
Copyright © 2011-2022 走看看