6-13 折半查找 (15 分)

給一個嚴格遞增數列,函數int Search_Bin(SSTable T, KeyType k)用來二分地查找k在數列中的位置。

函數接口定義:

int  Search_Bin(SSTable T, KeyType k)

其中T是有序表,k是查找的值。

裁判測試程序樣例:


#include <iostream>
using namespace std;

#define MAXSIZE 50
typedef int KeyType;

typedef  struct                     
{ KeyType  key;                                             
} ElemType;  

typedef  struct
{ ElemType  *R; 
  int  length;
} SSTable;                      

void  Create(SSTable &T)
{ int i;
  T.R=new ElemType[MAXSIZE+1];
  cin>>T.length;
  for(i=1;i<=T.length;i++)
     cin>>T.R[i].key;   
}

int  Search_Bin(SSTable T, KeyType k);

int main () 
{  SSTable T;  KeyType k;
   Create(T);
   cin>>k;
   int pos=Search_Bin(T,k);
   if(pos==0) cout<<"NOT FOUND"<<endl;
   else cout<<pos<<endl;
   return 0;
}

/* 請在這裏填寫答案 */

輸入格式:

第一行輸入一個整數n,表示有序表的元素個數,接下來一行n個數字,依次爲表內元素值。 然後輸入一個要查找的值。

輸出格式:

輸出這個值在表內的位置,如果沒有找到,輸出"NOT FOUND"。

輸入樣例:

5
1 3 5 7 9
7

輸出樣例:

4

輸入樣例:

5
1 3 5 7 9
10

輸出樣例:

NOT FOUND

關鍵點:不能嘗試修改更新T來使用遞歸,不然沒法獲取位置,因此只能使用循環來進行不斷查找;

int  Search_Bin(SSTable T, KeyType k)
{
    int start=0,end=T.length-1;
    while(start<=end)
    {
        int mid=(start+end)/2;
        if(T.R[mid].key==k)
        {
            return mid;
        }
        else if(T.R[mid].key>k)
        {
            end=mid-1;
        }
        else
        {
            start=mid+1;
        }
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章