60.7k views
3 votes
How does Binary Search work?

1) Starts at first element and goes up until it finds the "key" or if the list is sorted in ascending order, continues until the "key" is less than the current element
2) If a list is sorted in ascending order, split list in half then if the key is not in the middle element, if the element is less than the middle call the method for the left or if the element is more call the method for the right. If there is cross between high and low, then the element is not in the list.

User CasperOne
by
7.8k points

1 Answer

3 votes

Final answer:

Binary Search is a search algorithm used to find the position of a specific value within a sorted list. It repeatedly divides the list in half and compares the key with the middle element to determine the next search step.

Step-by-step explanation:

How does Binary Search work?

Binary Search is a search algorithm used to find the position of a specific value (key) within a sorted list. It works by repeatedly dividing the list in half and comparing the key with the middle element. Based on the comparison, it either continues searching the left or right half.

Step-by-Step Explanation:

  1. Start at the first element and the last element of the sorted list.
  2. Find the middle element by calculating the average of the first and last indices. If the middle element is equal to the key, the search is successful.
  3. If the key is less than the middle element, repeat the process for the left half of the list (from the first element to the middle element - 1).
  4. If the key is greater than the middle element, repeat the process for the right half of the list (from the middle element + 1 to the last element).
  5. Continue dividing the list in half and repeating the search until the key is found or there are no more elements to search.
  6. If the search reaches a point where the high index is less than the low index, the key is not in the list.
User Youngsup Kim
by
7.7k points