Binary Search recursive algorithm (with source code) _ ax

Source: Internet
Author: User

[Sequence]
Some things are very simple, but I forget it for a long time. So I wrote it here and copied it.

[Idea]
Put an index on both sides of the array to indicate that the number to be queried is within the range of the array Member values represented by the two indexes, and then keep narrowing the range (half-width reduction)

[Source code] The Axe helps the less helper

1 Using System;
2
3 Namespace Binarysearch
4 {
5 /**/ /// <Summary>
6///Binary Search Method, made by ax.
7/// </Summary>

8 Public   Class Search
9 {
10 Public   Static   Void Main ()
11 {
12 Int Searchkey = 8 ; // Number to be searched in the array
13 Int [] Scores = {2,4,6,8,10,12} ; // Array
14 Int Low = 0 ; // Minimum array index
15 Int High = Scores. Length - 1 ; // Maximum array index
16 Int Searchresult = Startsearch (scores, searchkey, low, high );
17 Console. writeline ( " The index of the number of queries is: " + Searchresult );
18 Console. Readline ();
19 }

20 Public   Static   Int Startsearch ( Int [] Arr, Int Key, Int Low, Int High)
21 {
22 If (Low > High)
23 {
24Return -1;
25}

26 Else
27 {
28 // The result is 6.0.
29 // Double AX = math. Round (5.5 );
30 // First execution (0 + 5)/2 = 2
31 Int Mid = (Low + High) / 2 ;
32 If (ARR [Mid] = Key)
33 {
34ReturnMid;
35}

36 Else   If (Key < Arr [Mid])
37 {
38ReturnStartsearch (ARR, key, low, mid-1);
39}

40 Else
41 {
42ReturnStartsearch (ARR, key, mid+1, High );
43}

44 }

45 }

46 }

47 }

48

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.