数据结构基础(5)-->二分查找
来源:互联网 发布:医药软件哪个好 编辑:程序博客网 时间:2024/05/19 18:37
#include <stdio.h>#include <string.h>#include <malloc.h>#include <stdlib.h>int binary_serch(int *arr, int arr_len, int value){int l = 0;int h = arr_len - 1;int m;while(l <= h) {m = l + ((h-l)>>1);if(value > arr[m]) {l = m + 1;} else if(value < arr[m]) {h = m - 1;} else {return m;}}return -1;}int main(int argc, char *argv[]){int pos;int arr[10] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};for(pos=0; pos<10; ++pos) {printf("%2d ", pos);}printf("\n");for(pos=0; pos<10; ++pos) {printf("%2d, ", arr[pos]);}printf("\n\n");pos = binary_serch(arr, 10, 9);printf(" 9's pos = %2d...\n", pos);pos = binary_serch(arr, 10, 1);printf(" 1's pos = %2d...\n", pos);pos = binary_serch(arr, 10, 19);printf(" 19's pos = %2d...\n", pos);pos = binary_serch(arr, 10, 10);printf(" 10's pos = %2d...\n", pos);pos = binary_serch(arr, 10, -10);printf("-10's pos = %2d...\n", pos);pos = binary_serch(arr, 10, 30);printf(" 30's pos = %2d...\n\n", pos);return 0;}
运行测试结果:
0 1 2 3 4 5 6 7 8 9 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 9's pos = 4... 1's pos = 0... 19's pos = 9... 10's pos = -1...-10's pos = -1... 30's pos = -1...
- 数据结构基础(5)-->二分查找
- 数据结构基础(2) --顺序查找 & 二分查找
- 数据结构基础 查找 之 二分查找
- 数据结构基础(2) --顺序查找 & 二分查找
- 数据结构基础(2) --顺序查找 & 二分查找
- 数据结构基础(2) --顺序查找 & 二分查找
- 一步一步复习数据结构和算法基础-顺序查找+二分查找
- 数据结构基础(10)------------二分查找算法(BinarySearch)
- 转贴:数据结构:二分查找
- 数据结构-二分查找算法
- [数据结构]二分查找
- 数据结构:二分查找算法
- 数据结构—二分查找
- 【Java数据结构】二分查找
- 数据结构--向量--二分查找
- 数据结构之二分查找
- 数据结构-二分查找
- 数据结构之二分查找
- 用VIM搭建Python开发环境
- linux内核空间与用户空间互访操作
- Session对象在各浏览器中的有效范围
- PHP explode() 函数
- Qt configure 参数说明
- 数据结构基础(5)-->二分查找
- ubuntu下eclipse环境配置
- 网卡的模式
- C# WORD操作实现代码
- LDD3源码分析之slab高速缓存
- 设计模式 (二)工厂方法模式(FactoryMethod)
- iPhone/Mac Objective-C内存管理教程和原理剖析
- extern用法详解(转)
- setsockopt设置socket状态