# The Magic Of O(Log N) Binary Search Algorithm

## Introduction

The binary search algorithm is one of the most popular and efficient search algorithms. It is used to search for a target value within a sorted array. The algorithm works by repeatedly dividing the search interval in half, ultimately reducing the search to a single element.

### What is O(log n)?

O(log n) is a measure of the time complexity of an algorithm. It means that the time taken by the algorithm increases logarithmically with the size of the input data. In the case of binary search, the time complexity is O(log n) because the search interval is divided in half at each step, reducing the search space by half.

## Binary Search Algorithm

The binary search algorithm is a divide and conquer algorithm that works on a sorted array. It starts by comparing the target value with the middle element of the array. If the target value is equal to the middle element, the search is successful. If the target value is less than the middle element, the search is continued on the left half of the array. If the target value is greater than the middle element, the search is continued on the right half of the array.

### Example

Let us consider an example to understand how binary search works. Suppose we have a sorted array of integers {1, 3, 5, 7, 9, 11, 13, 15, 17, 19} and we want to search for the value 11. The algorithm starts by comparing the target value 11 with the middle element 9. Since 11 is greater than 9, the search is continued on the right half of the array {11, 13, 15, 17, 19}. The algorithm then compares the target value 11 with the middle element 15. Since 11 is less than 15, the search is continued on the left half of the array {11, 13}. The algorithm then compares the target value 11 with the middle element 13. Since 11 is greater than 13, the search is continued on the right half of the array {11}. Finally, the algorithm compares the target value 11 with the middle element 11. Since 11 is equal to 11, the search is successful.