分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net
/* * Recursive Binary Search - by Chimomo * * [折半查找的前提]: * 1、待查找序列必须采用顺序存储结构。 * 2、待查找序列必须是按关键字大小有序排列。 * * 时间复杂度:O(log2n) */ namespace RecursiveBinarySearch { using System; /// /// The program. /// internal class Program { /// /// Entry point into console application. /// public static void Main() { int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9}; Console.WriteLine(BinarySearch(a, 6, 0, 9)); } /// /// 在下界为low,上界为high的有序数组a中折半查找数据元素x(递归查找)。 /// /// /// 待查找数组。 /// /// /// 目标元素。 /// /// /// 数组元素下标的下界。 /// /// /// 数组元素下标的上界。 /// ///
/// 若查找到目标元素则返回该目标元素在数组中的下标;否则返回-1。 ///
private static int BinarySearch(int[] arr, int x, int low, int high) { if (low > high) { return -1; } int mid = (low + high) / 2; if (x == arr[mid]) { return mid; } return x < arr[mid] ? BinarySearch(arr, x, low, mid - 1) : BinarySearch(arr, x, mid + 1, high); } } } // Output: /* 5 */
/* * Non-Recursive Binary Search - by Chimomo * * [折半查找的前提]: * 1、待查找序列必须采用顺序存储结构。 * 2、待查找序列必须是按关键字大小有序排列。 * * 时间复杂度:O(log2n) */ namespace NonRecursiveBinarySearch { using System; /// /// The program. /// internal class Program { /// /// Entry point into console application. /// public static void Main() { int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9}; Console.WriteLine(BinarySearch(a, 6, 9)); } /// /// 在长度为n的有序数组arr中查找值为x的元素(非递归查找)。 /// /// /// 待查找数组。 /// /// /// 目标元素。 /// /// /// 数组长度。 /// ///
/// 若查找到目标元素则返回该目标元素在数组中的下标;否则返回-1。 ///
private static int BinarySearch(int[] arr, int x, int n) { int low = 0; int high = n - 1; while (low <= high) { int mid = (low + high) / 2; if (arr[mid] == x) { return mid; } if (arr[mid] < x) { low = mid + 1; } else { high = mid - 1; } } return -1; } } } // Output: /* 5 */
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/228260.html原文链接:https://javaforall.net
