9.3 折半查找

折半查找(Binary Searching) 又称为对分查找(二分查找)是在查找表有序(升序或降序排列)的情况下进行的静态查找(即无添加、删除);

其查找过程是:先确定待查记录所在的范围,然后逐步缩小范围直到找到或找不到该记录为止。

注意点折半查找的效率比顺序查找的高,但折半查找只适用于有序表,其限于顺序存储结构(数组形式存储),对线性链表无法有效的进行折半查找。

折半查找时间复杂度:

      最佳状态复杂度为:B(n) = 1 ∈ O(n),

      最坏的情况是:W(n) = n ∈ O(logn)


1、在非递归情况下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/***********************************************************/
// 程序名称:BinarySearch.cpp
// 程序目的:设计一个线性查找的程序
// 程序来源:数据结构与算法分析(C语言描述) P-282
// 日期: 2013-8-28 8:46:03 JohnnyHu改进
/***********************************************************/

#include <stdio.h>
#include <stdlib.h>

#define  MAX  20
#define  NotFound  - 1
typedef  int ElementType;

ElementType data[MAX] = {    1214192225,
                             3239404547,
                             4853545960,
                             6869687077 };  // 数据数组

int BinarySerach( const ElementType a[], ElementType x,  int n);

// 主程序 
int main( void)
{
     int keyValue;
    printf( "请输入您要查找的(int)值,输入0退出: ");
     while(scanf( "%d", &keyValue))
    {
         if ( 0 == keyValue)
             break;
        
         int index = BinarySerach(data, keyValue, MAX);
         if (NotFound != index)
            printf( "您要查找的值是: data[%d] = %d \n", index, data[index]);
         else
            printf( "没找到!\n");

        printf( "请输入您要查找的(int)值,输入0退出: ");
    }

     return  0;
}

// 折半查找
int BinarySerach( const ElementType a[], ElementType x,  int n)
{
     int low, mid, high;

    low =  0;
    high = n - 1;
     while (low <= high)
    {
        mid = (low + high) /  2;
         if (a[mid] < x)
            low = mid +  1;
         else  if (a[mid] > x)
            high = mid -  1;
         else 
             return mid;  // 找到
    }

     return NotFound;     // 未找到
}

输出结果:


2、 在递归情况的下的折半查找:

修改函数:int BinarySerach(const ElementType a[], ElementType x, int n); 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 折半查找(递归)
int BinarySerach( int low,  int high,  int keyvalue)
{
     int mid = - 1;
    
     if (low > high)
         return NotFound;
     else 
    {
        mid = (low + high) /  2;
         if (data[mid] < keyvalue)
             return BinarySerach(mid+ 1, high, keyvalue);
         else  if (data[mid] > keyvalue)
             return BinarySerach(low, mid- 1, keyvalue);
         else 
             return mid;
    }

     return NotFound;     // 未找到
}

在主函数中

1
  int  index = BinarySerach(data, keyValue, MAX);

修改为

1
int index = BinarySerach( 0, MAX-1, keyValue);



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值