大挪耗

c++折半查找

#include "stdio.h"
#include "malloc.h"

typedef int InfoType;
typedef int KeyType;
typedef struct{
    KeyType key;
    InfoType data;
} RecType;

////顺序查找
//int SeqSearch(RecType R[],int n,KeyType k){
//    int i=0;
//    while (i<n && R[i].key!=k)
//        i++;
//    if (i>=0)
//        return 0;
//    else return i+1;
//}
//int SeqSearch1(RecType R[],int n,KeyType k){
//    int i=0;
//    R[n].key=k;
//    while (R[i].key!=k)
//        i++;
//    if (i==n)
//        return 0;
//    else return i+1;
//}
//折半查找
int BinSearch(RecType R[],int n,KeyType k){
    int low=0 ,high=n-1,mid;
    while (low<=high){
        mid=(low+high)/2;
        if (k==R[mid].key)
            return mid+1;
        if (k<R[mid].key)
            high=mid-1;
        else low=mid+1;

    }
    return 0;
}
//折半查找的扩展
int BinSearch2(RecType R[],int n,KeyType k){
    int low=0 ,high=n-1,mid;
    while (low<=high){
        mid=(low+high)/2;
        if (k<=R[mid].key){
            high=mid-1;
        } else low=mid+1;
    }
    return high+1;
}
int main(){
    RecType a[]={1,1,2,2,3,3,4,4,5,5,6,6
    ,7,7,8,8,9,9};
    printf("实验内容: 编写一个程序exp4-1.cpp,输出在顺序表(1,2,3,4,5,6,7,8,9,10)中采用折半查找方法查找关键字9的过程。\n");
    printf( "结果的位置是%d。\n",BinSearch(a,9,9));
}

输出:
实验内容: 编写一个程序exp4-1.cpp,输出在顺序表(1,2,3,4,5,6,7,8,9,10)中采用折半查找方法查找关键字9的过程。
结果的位置是9。


已发布

分类

可以收藏大挪耗一下。下载麻烦点城通网盘,站长保证下载速度,不会限速的,放心点就是了;分卷,安卓下载为txt:程序下载为url,不会下载参考不会下载。如果你想让本站活的久一点,请直接捐助

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注