码迷,mamicode.com
首页 > 其他好文 > 详细

折半查找<二分查找>

时间:2016-03-21 01:52:49      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:折半查找

折半条件:必须在一个有序数组内进行。

例如:在一个数组中查找一个数找到就输出该元素下标,如果没找到就输出-1:

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

int bin_search(int *p,int x, int n)

{

                 int left = 0;

                 int right = n - 1;

                 while (left <= right)

                {

                                 int i = 0;

                                i = ( right-left)/2+left; //(left&right) + ((left^right) >> 1)

                                                                  //right/2+left/2;

                                                                   //如果left和right很大,要防止left+right发生溢出

                                 if (p[i] > x)

                                {

                                                right = i - 1;

                                }

                                 else if (p[i] < x)

                                {

                                                left = i + 1;

                                }

                                 else

                                                 return i;

                }

                 return -1;

}

int main()

{

                printf( "请输入数组的大小:_" );

                 int n = 0;

                scanf( "%d", &n);

                printf( "请输入要查找的元素\n" );

                 int x = 0;

                scanf( "%d", &x);

                 int *p = (int *)calloc(n, sizeof( int));           //采用动态内存,提高对内存的利用

                 if (p == NULL)

                {

                                printf( "out of memory\n");

                                exit(1);

                }

                printf( "请初始化数组\n" );

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

                {

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

                }

                 int ret=bin_search(p,x,n);

                printf( "%d\n", ret);

                free(p);

                system( "pause");

                 return 0;

}


本文出自 “11132019” 博客,请务必保留此出处http://11142019.blog.51cto.com/11132019/1753283

折半查找<二分查找>

标签:折半查找

原文地址:http://11142019.blog.51cto.com/11132019/1753283

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!