二分搜索
来源:互联网 发布:用c语言打印出杨辉三角 编辑:程序博客网 时间:2024/05/18 02:42
二分搜索是一个分治算法。
个定已排好序的n个元素a[0:n-1],在这n个元素中找出某一特定的元素x。
二分搜索法的基本思路是把n个排好序的元素从中间分成大致相等的两部分,如果x==a[n/2],则找到x,如果x<a[n/2],在数组a的左半部分用相同的方法继续搜索,否则在右半部分搜索。
可以用以个递归的方法来实现二分搜索函数binary_search()。返回找到元素的下标。
#include <stdio.h>int binary_search(int[], int, int, int);int main(){ int a[5000], i=0, x, location; while(i<5000) { a[i] = i+1; i++; } printf("Please input a number you want :\n"); scanf("%d", &x); location = binary_search(a, 0, 4999, x); if(location==-1) printf("The number don't exist!\n"); else { printf("The number is %d", location+1); switch((location+1)%10) { case 1 : printf("st");break; case 2 : printf("nd");break; case 3 : printf("rd");break; default: printf("th");break; } printf(" in the array.\n"); } return 0;}int binary_search(int a[], int left, int right, int x){ int mid = (left+right)/2; if(left>right) return -1; if(a[mid]==x) return mid; if(x < a[mid]) return binary_search(a, left, mid-1, x); else return binary_search(a, mid+1, right, x);}
binary_search()这个函数也可以用非递归的方法实现,但是参数表需要做一些改变。
int binary_search(int a[], int length, int n)//return index of "n" in arrary "a"{ int left=0, right=length-1, mid; while(left <= right) { mid = (left + right)/2; if(n == a[mid]) return mid; if(n > a[mid]) left = mid+1; else right = mid-1; } return -1;}
这个算法的时间复杂度为O(log n)
运行效果:
Please input a number you want :
4321
The number is 4321st in the array.
- 二分搜索
- 二分搜索
- 二分搜索
- 二分搜索
- 二分搜索
- 二分搜索
- 二分搜索
- 二分搜索
- 二分搜索
- 二分搜索
- 二分搜索
- 二分搜索
- 二分搜索
- 二分搜索
- 二分搜索
- 二分搜索
- 二分搜索
- 二分搜索
- Ubuntu12上安装Oracle11gR2
- 找错题
- SH配置中,hibernate不会自动释放session conn程序卡死
- 设计应注意的细节
- 使用JSR 181注解导出Web Service
- 二分搜索
- XFire为访问服务端Web Service的方式
- FastDFS安装过程中出现的问题
- Linux下 查看当前目录的所有文件
- 白话SqlConnection,SqlCommand,SqlDataAdapter,SqlDataReader,DataSet
- xfire使用注解的方式发布webService
- jQuery选择器中含有空格的注意事项
- CXF 开发webService的步骤(java First)
- Could not find wsdl:binding operation info for web method sayHi