Home 数据结构及算法 折半法查找

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

int Dichotomy_Match(int *Array,int ArrayLength,int Elem)
{
    //传入数组由小到大排列
    int *head=NULL,*end=NULL,*mid=NULL;

    head=Array;
    end=&Array[ArrayLength-1];
    mid=&Array[ArrayLength/2-1];

    while(1)
    {
        if(end-head<0 || mid-Array>=ArrayLength || mid-Array<0) return 0;
        if(*mid==Elem) return 1;
        if(*mid<Elem)
        {
            head=mid+1;
            mid+=(end-head)/2+1;
            continue;
        }
        if(*mid>Elem)
        {
            end=mid-1;
            mid-=(end-head)/2+1;
            continue;
        }
    }

    return 0;
}

int main()
{
    int number[10],elem;
    int i;

    printf(“请输入十个递增整数:\n”);
    for(i=0; i<10; i++)
        scanf(“%d”,&number[i]);
    printf(“请输入查找的元素:”);
    scanf(“%d”,&elem);
    i=Dichotomy_Match(number,sizeof(number)/4,elem);
    if(i)
        printf(“TRUE”);
    else
        printf(“FALSE”);
    puts(“”);
    getch();

    return 0;
}

 

 

 

 

打赏
0 comment

You may also like

Leave a Comment

*

code

error: Alert: Content is protected !!