數據結構課后練習題(練習一)習題1.8 二分查找 (20 分)


本題要求實現二分查找算法。

函數接口定義:

Position BinarySearch( List L, ElementType X ); 

其中List結構定義如下:

typedef int Position; typedef struct LNode *List; struct LNode { ElementType Data[MAXSIZE]; Position Last; /* 保存線性表中最后一個元素的位置 */ }; 

L是用戶傳入的一個線性表,其中ElementType元素可以通過>、=、<進行比較,並且題目保證傳入的數據是遞增有序的。函數BinarySearch要查找XData中的位置,即數組下標(注意:元素從下標1開始存儲)。找到則返回下標,否則返回一個特殊的失敗標記NotFound

裁判測試程序樣例:

#include <stdio.h> #include <stdlib.h> #define MAXSIZE 10 #define NotFound 0 typedef int ElementType; typedef int Position; typedef struct LNode *List; struct LNode { ElementType Data[MAXSIZE]; Position Last; /* 保存線性表中最后一個元素的位置 */ }; List ReadInput(); /* 裁判實現,細節不表。元素從下標1開始存儲 */ Position BinarySearch( List L, ElementType X ); int main() { List L; ElementType X; Position P; L = ReadInput(); scanf("%d", &X); P = BinarySearch( L, X ); printf("%d\n", P); return 0; } /* 你的代碼將被嵌在這里 */ 

輸入樣例1:

5
12 31 55 89 101
31

輸出樣例1:

2

輸入樣例2:

3 26 78 233 31 

輸出樣例2:

0 

鳴謝寧波大學 Eyre-lemon-郎俊傑 同學修正原題!

Position BinarySearch(List L,ElementType X){
    int l=0;int r=L->Last;
    int m=L->Last/2;int coun=L->Last;
    while(coun--){
        if(L->Data[m]==X) return m;
        if(L->Data[m]<X){
            l=m;
            m=(l+r)/2+1;//大數據查找最后一個數字,這邊要進行加一操作,這個case容易出錯
            continue;
        }
        if(L->Data[m]>X){
            r=m;
            m=(l+r)/2;
        }
    }
    return NotFound;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM