menu search
brightness_auto
more_vert
logic of the program?
thumb_up_off_alt 2 like thumb_down_off_alt 0 dislike

1 Answer

more_vert
 
verified
Best answer
  1. Input: Receive a sorted array arr of 10 elements and a number num to be searched.

  2. Initialize: Set first to 0 (the index of the first element) and last to 9 (the index of the last element). Calculate middle as the average of first and last.

  3. Binary Search Loop:

    • Enter a while loop as long as first is less than or equal to last.
    • Check the middle element:
      • If it is less than num, update first to middle + 1.
      • If it is equal to num, print the position and exit the loop.
      • If it is greater than num, update last to middle - 1.
    • Recalculate middle based on the updated first and last.
  4. Output:

    • If first is greater than last, the number num is not found in the array.
    • Print the result.
  5. End: The program ends, returning 0.

In essence, binary search works by repeatedly dividing the search interval in half. If the middle element is equal to the target, the search is successful. If the middle element is less than the target, the search continues in the right half; otherwise, it continues in the left half. This process repeats until the target is found or the search interval is empty.

thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike

Related questions

thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike
1 answer
thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike
0 answers
thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike
1 answer
thumb_up_off_alt 1 like thumb_down_off_alt 0 dislike
1 answer
thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike
1 answer
thumb_up_off_alt 1 like thumb_down_off_alt 0 dislike
0 answers

Doubtly is an online community for engineering students, offering:

  • Free viva questions PDFs
  • Previous year question papers (PYQs)
  • Academic doubt solutions
  • Expert-guided solutions

Get the pro version for free by logging in!

5.7k questions

5.1k answers

108 comments

648 users

...