# Binary Search

#### In this tutorial, you will learn how Binary Search sort works. Also, you will find working examples of Binary Search in Python.

Binary Search is a searching algorithm for finding an element’s position in a sorted array.

In this approach, the element is always searched in the middle of a portion of an array.

Binary search can be implemented only on a sorted list of items. If the elements are not sorted already, we need to sort them first.

## Binary Search Working

Binary Search Algorithm can be implemented in two ways which are discussed below.

1. Iterative Method
2. Recursive Method

The recursive method follows the divide and conquer approach.

The general steps for both methods are discussed below.

1. The array in which searching is to be performed is:

Let `x = 4` be the element to be searched.

2. Set two pointers low and high at the lowest and the highest positions respectively.
3. Find the middle element mid of the array ie. `(arr[low + high]) / 2 = 6`.
4. If x == mid, then return mid.Else, compare the element to be searched with m.
5. If `x > mid`, compare x with the middle element of the elements on the right side of mid. This is done by setting low to `low = mid + 1`.
6. Else, compare x with the middle element of the elements on the left side of mid. This is done by setting high to `high = mid - 1`.
7. Repeat steps 3 to 6 until low meets high.
8. `x = 4` is found.

## Binary Search Algorithm

### Iteration Method

```do until the pointers low and high meet each other.
mid = (low + high)/2
if (x == arr[mid])
return mid
else if (x > A[mid]) // x is on the right side
low = mid + 1
else                       // x is on the left side
high = mid - 1```

### Recursive Method

```binarySearch(arr, x, low, high)
if low > high
return False
else
mid = (low + high) / 2
if x == arr[mid]
return mid
else if x < data[mid]        // x is on the right side
return binarySearch(arr, x, mid + 1, high)
else                               // x is on the right side
return binarySearch(arr, x, low, mid - 1)```

## Python Examples (Iterative Method)

``````/* Binary Search in python */

def binarySearch(array, x, low, high):

/* Repeat until the pointers low and high meet each other */
while low <= high:

mid = low + (high - low)//2

if array[mid] == x:
return mid

elif array[mid] < x:
low = mid + 1

else:
high = mid - 1

return -1

array = [3, 4, 5, 6, 7, 8, 9]
x = 4

result = binarySearch(array, x, 0, len(array)-1)

if result != -1:
print("Element is present at index " + str(result))
else:

## Python Examples (Recursive Method)

``````/* Binary Search in python */

def binarySearch(array, x, low, high):

if high >= low:

mid = low + (high - low)//2

/* If found at mid, then return it */
if array[mid] == x:
return mid

/* Search the left half */
elif array[mid] > x:
return binarySearch(array, x, low, mid-1)

/* Search the right half */
else:
return binarySearch(array, x, mid + 1, high)

else:
return -1

array = [3, 4, 5, 6, 7, 8, 9]
x = 4

result = binarySearch(array, x, 0, len(array)-1)

if result != -1:
print("Element is present at index " + str(result))
else:

## Binary Search Complexity

Time Complexities

• Best case complexity`O(1)`
• Average case complexity`O(log n)`
• Worst case complexity`O(log n)`

Space Complexity

The space complexity of the binary search is `O(n)`.

## Binary Search Applications

• In libraries of Java, .Net, C++ STL
• While debugging, the binary search is used to pinpoint the place where the error happens.

# Special 95% discount

## Two Machine Learning Fields

There are two sides to machine learning:

• Practical Machine Learning:This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.
• Theoretical Machine Learning: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.

Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes

Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!

Latest end-to-end Learn by Coding Recipes in Project-Based Learning:

Applied Statistics with R for Beginners and Business Professionals

Data Science and Machine Learning Projects in Python: Tabular Data Analytics

Data Science and Machine Learning Projects in R: Tabular Data Analytics

Python Machine Learning & Data Science Recipes: Learn by Coding

R Machine Learning & Data Science Recipes: Learn by Coding

Comparing Different Machine Learning Algorithms in Python for Classification (FREE)

`Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.  `