二分(折半)查找算法实现
2015-07-05 17:04
405 查看
不多说了,见代码:
// BinaryFindNumINArray.cpp : 定义控制台应用程序的入口点。 /* @mishidemudong @2015-7-5-17:02 */ // #include "stdafx.h" #include<iostream> using namespace std; bool Find=false; int BinaryFind(int *a,int length, int target) { if (a == NULL || length < 0) return -1; int low = 0, high = length - 1; int mid = 0; while (low <= high) { if (a[mid] == target) { Find = true; return mid; break; } mid = (low + high) / 2; if (a[mid] < target) low = mid; else high = mid; } }
//递归版本
<pre name="code" class="cpp">int BinerarySearch(int a[], int low, int high, int key) { int mid = 0; if (low > high) return -1; else { mid = (low + high) / 2; if (a[mid] == key) return mid; if (key > a[mid] ) return BinerarySearch(a, mid + 1, high, key); else return BinerarySearch(a, low, mid - 1, key); } }
int _tmain(int argc, _TCHAR* argv[]) { int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 19, 30, 58 }; int length = sizeof(a)/sizeof(int); int location = 0; int x = 0; for (int i = 0; i < length; ++i) cout << a[i]<< " "; cout << endl; cout << "whitch number do you want to seach?"; scanf_s("%d", &x); location = BinaryFind(a, length,x); switch (Find) { case true:printf("Yes,The number you input is founded!And it is %dth number in the array.", location + 1); break; case false:printf("Sorry,The number you input is not in this Array."); } return 0; }
相关文章推荐
- Ubuntu 下 触摸板不能使用 解决方法
- LeetCode: Distinct Subsequences [115]
- 工作日志--mfcButton和线程
- Android中的Data Binding初探 (一)
- 【LeetCode 110_二叉树_遍历】Balanced Binary Tree
- 在 VC 中,让调试器带上符号调试
- nsq源码导读(序)
- curl获取12306订票信息
- Rails当你运行一个数据库回滚错误:ActiveRecord::IrreversibleMigration exception
- jboss 5.0 安装配制负载均衡
- JAVA CAS原理深度分析
- (转)python中集合的运算
- leetcode:Summary Ranges
- HDU 1043 Eight (BFS·八数码·康托展开)
- SQL 从指定表筛选指定行信息 获取表行数
- VB获取本机网卡类型、IP、MAC地址
- I/O系统
- The Buses (poj 1167 搜索)
- 如何修改MFC发布程序的图标
- PHP 错误与异常 笔记与总结(15 )使用观察者模式处理异常信息