折半查找<二分查找>

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了折半查找<二分查找>相关的知识,希望对你有一定的参考价值。

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

例如:在一个数组中查找一个数找到就输出该元素下标,如果没找到就输出-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

以上是关于折半查找<二分查找>的主要内容,如果未能解决你的问题,请参考以下文章

二分查找法,折半查找原理

二分查找/折半查找

折半查找

二分查找(折半查找)

java 二分查找 - 折半查找算法

php查找之二分查找