二分查找(binary search)

来源:互联网 发布:药学网络本科 编辑:程序博客网 时间:2024/04/27 11:52

二分查找:又称折半查找,优点是比较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表,且插入删除困难。

实例代码:

//binary search array#include "stdafx.h"#include <iostream>using std::cout;using std::endl;int BinarySearch(int *data, int nLen, int nSought){if (nLen < 1){return -1;}int low = 0;int hight = nLen - 1;int mid = (low + hight) / 2;while (low <= hight){if (data[mid] == nSought){return mid;}else if (data[mid] < nSought){low = mid + 1;}else{hight = mid - 1;}mid = (low + hight) / 2;}return -1;}int _tmain(int argc, _TCHAR* argv[]){int data[] = { 1, 3, 4, 5, 7, 9 };int nlen = sizeof(data) / sizeof(int);int nSought = 6;int nret = BinarySearch(data, nlen, nSought);if (nret == -1){cout << "没有查找到: " << nSought << endl;}else{cout << nSought << " 索引是:" << nret << endl;}return 0;}


0 0
原创粉丝点击