Binary search, binarysearch
- // Configure //--------------------------------------------------------------------------------------------------------------------
- // <Copyright company = "Chimomo's Company" file = "Program. cs">
- // Respect the work.
- // </Copyright>
- // <Summary>
- // The binary search (not recursive ).
- // [Prerequisites for searching in half]:
- // 1. The sequence to be searched must adopt a sequential storage structure.
- // 2. The sequence to be searched must be ordered by the keyword size.
- /// </Summary>
- // Configure //--------------------------------------------------------------------------------------------------------------------
- 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>
- /// Search for elements whose values are key (non-recursive search) in an ordered array a with a length of n ).
- /// </Summary>
- /// <Param name = "a">
- /// The array to be searched.
- /// </Param>
- /// <Param name = "key">
- /// Target element.
- /// </Param>
- /// <Param name = "n">
- /// Array length.
- /// </Param>
- /// <Returns>
- /// If the target element is found, the subscript of the target element in the array is returned; otherwise,-1 is returned.
- /// </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
- */
- Time Complexity: O (log2n)