您的位置:首页 > 其它

采用二分查找(即折半查找)的方法实现查找

2016-11-29 14:34 239 查看
 
采用二分查找的方法实现查找

(1)定义顺序表的存储结构;

(2)实现顺序表上二分查找;

代码实现:

#include<iostream>

#include<stdio.h>

#include<cstdio>

#include<string.h>

#include<cstring>

#include<string>

#include<queue>

#include<malloc.h>//头文件包含malloc函数,用来申请内存空间

#include<algorithm>

#include<math.h>

using namespace std;

#define TRUE 1

#define FALSE 0

#define OK 1

#define ERROR 0

#define OVERFLOW -2

#define INFEASIBLE -1

#define N 10 // 数据元素个数

typedef int Status;//Status是函数的类型,其值是函数结果状态代码

typedef int KeyType; // 设关键字域为整型

//数据元素的类型  

struct ElemType

{

    int key;

};

//静态查找表的顺序存储结构  

struct SSTable

{

    ElemType *elem;//数据元素的存储空间的基地址,(0号单元不用)  

    int length;//表的长度  

};

//对于两个数值型变量的比较约定为如下的宏定义  

#define EQ(a,b) ((a) == (b))  

#define LT(a,b) ((a) < (b))  

#define LQ(a,b) ((a) <= (b))  

//由n个数据元素的数组r,构造静态查找表ST  

void Create_Seq(SSTable &ST, ElemType r[], int n)

{

    int i;

    //ST.elem=(ElemType*)calloc(n+1,sizeof(ElemType));//动态生成n+1个数据元素空间,0号单元不用  

    ST.elem = (ElemType*)malloc((n + 1)*sizeof(ElemType));

    if (!ST.elem)

        exit(ERROR);

    for (i = 1; i <= n; i++)

        ST.elem[i] = r[i - 1];//将数组的元素依次赋值给ST  

    ST.length = n;

}

void Ascend(SSTable &ST)//重建静态查找表为按照关键字为非降序排列  

{

    int i, j, k;

    for (i = 1; i < ST.length; i++)

    {

        k = i;

        ST.elem[0] = ST.elem[i];//待比较的元素存入0号单元  

        for (j = i + 1; j <= ST.length; j++)

        {

            if (LT(ST.elem[j].key, ST.elem[0].key))

            {

                k = j;

                ST.elem[0] = ST.elem[j];

            }

        }

        if (k != i)//有更小的值则交换  

        {

            ST.elem[k] = ST.elem[i];

            ST.elem[i] = ST.elem[0];

        }

    }

}

//在有序表ST中,折半查找关键字等于key的数据元素,返回在表中的位置(查找有序的顺序表)  

int Search_Bin(SSTable &ST, long key)

{

    int low, mid, high;

    low = 1;

    high = ST.length;//置区间初值  

    while (low <= high)

    {

        mid = (low + high) / 2;

        if (EQ(ST.elem[mid].key, key))

            return mid;

        else if (LT(key, ST.elem[mid].key))

            high = mid - 1;//继续在前半个区间查找  

        else

            low = mid + 1;//继续在后半个区间查找  

    }

    return 0;//没有查找到  

}

//顺序表的有序查找  

int main()

{

    SSTable st;

    int i,n;

    int s;

    ElemType r[50];

    printf("请输入您所要查找的序列的元素个数:");

    scanf("%d", &n);

    printf("请按照从小到大的顺序输入各元素的值:");

    for (int i = 0; i < n; i++) {

        scanf("%d", &r[i]);

    }

    Create_Seq(st, r, n);//建立无序的顺序查找表  

    Ascend(st);//将无序的查找表重建为按照关键字非降序排列的查找表  

    printf("请输入你要查找值得关键字:");

    scanf("%d", &s);

    i = Search_Bin(st, s);

    if (i)

        printf("存在您要找的关键字%d,且是第%d个关键字\n", st.elem[i].key, i);

    else

        printf("不存在您要找的关键字!");

    return 0;

}

执行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二分查找
相关文章推荐