- 递归实现:
[csharp]
view plain
copy
print
?
- // ——————————————————————————————————————–
- // <copyright company=”Chimomo’s Company” file=”Program.cs”>
- // Respect the work.
- // </copyright>
- // <summary>
- // The binary search (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, 0, 9));
- }
- /// <summary>
- /// 在下界为low,上界为high的有序数组a中折半查找数据元素x(递归查找)。
- /// </summary>
- /// <param name=”a”>
- /// 待查找数组。
- /// </param>
- /// <param name=”x”>
- /// 目标元素。
- /// </param>
- /// <param name=”low”>
- /// 数组元素下标的下界。
- /// </param>
- /// <param name=”high”>
- /// 数组元素下标的上界。
- /// </param>
- /// <returns>
- /// 若查找到目标元素则返回该目标元素在数组中的下标;否则返回-1。
- /// </returns>
- private static int BinarySearch(int[] a, int x, int low, int high)
- {
- if (low > high)
- {
- return -1;
- }
- int mid = (low + high) / 2;
- if (x == a[mid])
- {
- return mid;
- }
- return x < a[mid] ? BinarySearch(a, x, low, mid – 1) : BinarySearch(a, x, mid + 1, high);
- }
- }
- }
- // Output:
- /*
- 5
- */
时间复杂度:O(log2n)
- 非递归实现:
[csharp]
view plain
copy
print
?
- // ——————————————————————————————————————–
- // <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)
转自:http://blog.csdn.net/troubleshooter/article/details/4621272