查找--二分查找
2016-06-23 15:41
369 查看
二分查找的前提是线性表中的记录必须是有序的,线性表必须采用顺序存储。
二分查找的基本思想是:
1.在有序表中,取中间记录作为比较对象,若给定值与中间记录的值相等,则查找成功;
2.若给定值小于中间记录的值,则在中间记录的左半区继续查找;
3.若给定值大于中间记录的值,则在中间记录的右半区继续查找;
二分查找的时间复杂度是:O(logn)
二分查找的基本思想是:
1.在有序表中,取中间记录作为比较对象,若给定值与中间记录的值相等,则查找成功;
2.若给定值小于中间记录的值,则在中间记录的左半区继续查找;
3.若给定值大于中间记录的值,则在中间记录的右半区继续查找;
二分查找的时间复杂度是:O(logn)
C 版
// binary search c.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" int binary_search(int* arr, int length, int target) { int first = 0 ; int last = length - 1 ; int mid = (first + last) / 2 ; while (first <= last) { if (arr[mid] < target) { first = mid ; } else if (arr[mid] > target) { last = mid ; } else { return mid ; } mid = (first + last) / 2 ; } return 0 ; } int _tmain(int argc, _TCHAR* argv[]) { int arr[] = {0, 1, 16, 24, 35, 47, 59, 62, 73, 88, 99}; int length = 11; int result = binary_search(arr, length, 62); return 0; }
C++ 版
// binary search c++.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <vector> using namespace::std; int binary_search(vector<int>& vec, int target) { int first = 0 ; int last = vec.size() - 1 ; int mid = (first + last) / 2 ; while (first <= last) { if (vec[mid] < target) { first = mid ; } else if (vec[mid] > target) { last = mid ; } else { return mid ; } mid = (first + last) / 2 ; } return 0 ; } int _tmain(int argc, _TCHAR* argv[]) { int arr[] = {0, 1, 16, 24, 35, 47, 59, 62, 73, 88, 99}; vector<int> test(arr, arr + 11); int result = binary_search(test, 62); return 0; }
C# 版
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace binary_search_CSharp { class Program { static int binary_search(int[] arr, int target) { int first = 0; int last = arr.Length - 1; int mid = (first + last) / 2; while ( first <= last ) { if ( arr[mid] < target ) { first = mid; } else if ( arr[mid] > target ) { last = mid; } else { return mid; } mid = (first + last) / 2; } return 0; } static void Main(string[] args) { int[] arr = { 0, 1, 16, 24, 35, 47, 59, 62, 73, 88, 99 }; int result = binary_search(arr, 62); return; } } }
相关文章推荐
- TFS 2015 敏捷开发实践 – 看板的使用
- Linux系统性能分析(一)
- wget 抓取网站模版
- springMVC的ajax请求
- 虚幻4 内存优化工具
- TFS 2015 敏捷开发实践 – 看板的使用
- TFS 2015 敏捷开发实践 – 看板的使用
- pylot网站压力测试
- 短序列组装Sequence Assembly(转载)
- ASP.Net MVC开发基础学习笔记:四、校验、AJAX与过滤器
- 面试题13:在O(1)时间内删除链表结点
- Exchange 2010的搭建与配置
- C# 拖拽下载实现
- java lambda学习
- TFS 2015 敏捷开发实践 – 看板的使用
- C# 右下角弹出窗口
- linux apr安装
- photoview-library 图片的缩放
- 在Android Studio中遇到seesion App Error installing APK解决办法
- 使用RelativeLayout时,android:layout_toEndOf="@/id/xxxx",还是"@+id/xxxx"