算法 binary search
- // --------------------------------------------------------------------------------------------------------------------
- // <copyright company="Chimomo's Company" file="Program.cs">
- // Respect the work.
- // </copyright>
- // <summary>
- // The binary search (not recursive).
- // [折半查找的前提]:
- // 1、待查找序列必须採用顺序存储结构。
-
// 2、待查找序列必须是按keyword大小有序排列。
- // </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)