Binary Search algorithm – Data Structure and Algorithm
Binary search is an algorithm used to find the position of a target value within a sorted array. The algorithm works by repeatedly dividing the search interval in half and comparing the target value to the middle element of the array. If the target value matches the middle element, the search is successful. Otherwise, the search continues in the lower or upper half of the array, depending on whether the middle element is greater or less than the target value.
Binary search is a commonly used search algorithm in computer science that works by repeatedly dividing the search interval in half. It is a very efficient algorithm for searching sorted arrays or lists.
Here's how binary search works:
-
Given a sorted list of elements, the algorithm compares the target value to the middle element of the list.
-
If the target value is equal to the middle element, the search is complete and the index of the middle element is returned.
-
If the target value is less than the middle element, the search continues on the lower half of the list.
-
If the target value is greater than the middle element, the search continues on the upper half of the list.
-
The search interval is halved at each iteration until the target value is found or the search interval is empty.
Here's an example of how binary search works:
Suppose you have a sorted array of integers as follows:
let arr = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
And you want to find the position of the value 10
in the array.
- Start by defining two pointers:
left
andright
. Setleft
to the first index of the array (which is0
) andright
to the last index of the array (which is9
). - Calculate the middle index of the array as
mid = (left + right) // 2
(integer division). - Compare the target value (
10
) with the middle element of the array (arr[mid]
). In this case,arr[mid]
is10
, so the search is successful and we returnmid
. - If the target value is less than the middle element (
arr[mid]
), then setright
tomid - 1
and repeat step 2. - If the target value is greater than the middle element (
arr[mid]
), then setleft
tomid + 1
and repeat step 2.
For example, let's say we want to find the position of the value 16
in the array:
left = 0
,right = 9
.mid = (0 + 9) // 2 = 4
.arr[mid] = 10
is less than16
, so we setleft = mid + 1 = 5
and repeat step 2.mid = (5 + 9) // 2 = 7
.arr[mid] = 16
is equal to the target value, so we returnmid = 7
.
Binary search has a time complexity of O(log n), which makes it very efficient for large lists or arrays.
Latest
SOLID Principles: A Comprehensive Guide with Examples
News
Pure html popover API is coming in Chromium 114
Featured
SOLID Principles: A Comprehensive Guide with Examples