+2 votes
in Programming by
edited by
logic of the program?

1 Answer

0 votes
by (98.9k points)
selected by
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.

Related questions

0 votes
0 answers 136 views
+1 vote
1 answer 153 views

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


530 users