当前位置:编程学习 > C/C++ >>

二分查找的一个版本

 

#include <stdio.h>

#include <stdlib.h>

#define  NUM   100

typedef struct node

{

        int x;

        int y;

}node ;

node  global[NUM]={-999};

int  count=0;

int find(int left,int right,node x)

{

        int  mid =(left +right )/2;

        if (left==mid )

        {  

                 if(  x.x==global [right].x)

                        return  right;

                else  if(  x.x==global [left].x)

                        return  left;

                else

                        return   -1;

        } 

        else if( x.x > global [ mid  ].x  )

                return  find  ( mid  ,right ,x );

        else

                return  find (left ,  mid ,  x);

 

}

 

int  main()

{

        int i=0,j=0;

        struct node temp;

        for(i=0;i<NUM;i++)

        {

                j=i*i;

                temp.x=j;

                printf("  (%d)  ",temp.x);

                global[i].x=j;

        }

        printf("\n");

        temp.x=0;

        find ( 0,NUM-1,temp);

        for(i=0;i<NUM;i++)

        {

                temp.x=global[i].x;

                printf("result is  {%d } \n",  find ( 0 , NUM-1 , temp));

        }

 

        printf("new\n ");

 

        while ( scanf("%d",&j) && j )

        {

                temp.x=j;

                printf("result is  {%d } \n",  find ( 0 ,NUM-1 , temp));

        }

}

摘自 chenbingchenbing的专栏

补充:软件开发 , C语言 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,