算法 binary search
来源:互联网 发布:淘宝购物评级一颗星 编辑:程序博客网 时间:2024/05/21 09:56
- // --------------------------------------------------------------------------------------------------------------------
- // <copyright company="Chimomo's Company" file="Program.cs">
- // Respect the work.
- // </copyright>
- // <summary>
- // The binary search (not recursive).
- // [折半查找的前提]:
- // 1、待查找序列必须采用顺序存储结构。
- // 2、待查找序列必须是按关键字大小有序排列。
- // </summary>
- // --------------------------------------------------------------------------------------------------------------------
- namespace CSharpLearning
- {
- using System;
- /// <summary>
- /// The program.
- /// </summary>
- internal class Program
- {
- /// <summary>
- /// Entry point into console application.
- /// </summary>
- public static void Main()
- {
- int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
- Console.WriteLine(BinarySearch(a, 6, 9));
- }
- /// <summary>
- /// 在长度为n的有序数组a中查找值为key的元素(非递归查找)。
- /// </summary>
- /// <param name="a">
- /// 待查找数组。
- /// </param>
- /// <param name="key">
- /// 目标元素。
- /// </param>
- /// <param name="n">
- /// 数组长度。
- /// </param>
- /// <returns>
- /// 若查找到目标元素则返回该目标元素在数组中的下标;否则返回-1。
- /// </returns>
- private static int BinarySearch(int[] a, int key, int n)
- {
- int low = 0;
- int high = n - 1;
- while (low <= high)
- {
- int mid = (low + high) / 2;
- if (a[mid] == key)
- {
- return mid;
- }
- if (a[mid] < key)
- {
- low = mid + 1;
- }
- else
- {
- high = mid - 1;
- }
- }
- return -1;
- }
- }
- }
- // Output:
- /*
- 5
- */
- 时间复杂度:O(log2n)
0 0
- 算法 binary search
- 数据结构与算法:Binary search
- 【算法总结】Binary search 二分法
- 二分查找算法(Binary Search)的实现
- 二分查找算法(Binary Search)的实现
- 折半检索算法——Binary Search
- leetcode99 Recover Binary Search Tree java 算法
- 算法-- 2分查找 Binary Search
- LeetCode算法题目:Recover Binary Search Tree
- LeetCode算法题目:Unique Binary Search Trees
- LeetCode算法题目:Validate Binary Search Tree
- 算法训练:Unique Binary Search Trees
- 【算法总结】Binary Tree & Binary Search Tree 二叉树
- Binary search
- Binary Search
- Binary Search
- binary search
- binary search
- The content of element type "session-factory" must match "(property*,mapping*,(class-cache| collect
- 职责链模式
- oracle关闭listener.log日志
- C++对象模型-笔记三
- Android UI - 实现广告Banner轮播效果
- 算法 binary search
- 【BZOJ 3529】 [Sdoi2014]数表
- 响应式网页设计
- 数据链路层和网络层
- Python基础11--匿名函数和偏函数
- 左右连接,oracle11版本中的bug
- chattr命令
- Fire Net
- 设计Kafka的High Level Consumer