Skip to main content

Implementing binary search of an array in Java and Python

A binary search divides a range of ordered values into halves (two equal portions) and continues to split the array until the position of unknown value is found. It is an example of a "divide and conquer" algorithm. One of the common ways to use binary search is to find an unknown item in an array. It has the run-time complexity of O(log n).

An array is a container object that holds a fixed number of values of a single type. In Java programming language the length of an array is established when the array is created. But in Javascript, neither the length of a JavaScript array nor the types of its elements are fixed. Python programming language considers arrays as lists that can contain mixed data types.

Following paragraphs try to describe the binary search in details.

Binary search works with only sorted collections. That is due to the binary search looks for a particular item by comparing the middle element of the array. If it matches the item we look for, the index of the item is returned. If the item we are looking for is greater than the middle item, then the item is searched in the sub-array (array is divided into two sub-arrays) to the left of the middle item. Otherwise, the item is searched for in the sub-array to the right of the middle item. This process continues on the sub-arrays until the size of the sub-array reduces to zero.

The following is our sorted array and let us assume that we need to search the location of value 11 using binary search.

First, we need to find the middle item of the array using following formula.

middle index = lowest index + (highest index - lowest index) / 2

By using the above formula we get the 0 + (9 - 0 ) / 2 = 4.5 (round it) as middle index. So the fourth item is the middle item.



The value stored in the fourth position is less than the value we are looking for, so the value must be in the upper position of the array.


Again we use the above formula to find the middle index. Now lowest index value is equal to the previous value of middle index + 1. Because we are in the upper position of the array.

lowest index = middle index (4) + 1

middle index = lowest index + (highest index - lowest index) / 2

Now the middle index is 7. But the value we are searching for is number 11.


Now we need to change the direction of the search.


Now we have a sub-array with 11 and 15. But the highest index is lowest index - 1 and the lowest index is same as the previous time.

highest index = middle index (7) - 1

middle index = lowest index + (highest index - lowest index) / 2

Now it will check the first element and get the value to compare. Value is 11 and we are looking for 11. 

Pseudocode for binary search


Pseudocode is an artificial and informal language that helps programmers develop and understand algorithms. Due to the differences between programming languages, it is a wise step to write the algorithm using pseudocode. 

An algorithm is merely the sequence of steps taken to solve a problem. To implement any algorithm, you must be able to understand every detail of the problem.


I have tried to write the pseudocode in plain English for the beginners.

  1. Define lowest_index as 0 and the highest index as length of the array.
  2. Compute middle array.
  3. Compare the middle array with the value we need to search.
  4. If the middle array value (not index) equal to the value we are searching for return it.
  5. If the value we searching for is too large, that is, middle item > value we search then the highest index - 1.
  6. Otherwise, the guess is too small set the middle_index + 1.
  7. Go back to step two.

Python code for binary search


Here is the python code sample for the binary search. It is the recursive implementation of the binary search. You can copy the code using the following gist.


Java code for binary search


Here is the Java code sample for the binary search. You can copy the code using the following gist.


There are lots of resources to understand binary search. The following video by CS50 explains the algorithm visually. If you are a visual learner, you can watch the following video to understand the algorithm.

Comments

Popular posts from this blog

Alternatives to the SQLite in Android

At the moment there are several embeddable databases and libraries out there that you can use in a mobile application. In this post, I examine most popular libraries and databases and highlight some of their characteristics. Realm Realm is a mobile platform and a replacement for SQLite & Core Data. According to the website, it has more than 100k active developers. Realm is fully open source and distributes under Apache License. Realm Mobile Database is much faster than an ORM, and often faster than raw SQLite due to zero-copy design. Some of the benefits of Realm are fast queries, safe threading, encryption of data and reactive architecture. You can learn more about Realm by visiting this page . Sugar ORM Sugar ORM is a library that can be used to interact with SQLite database using Object-Relational Mapping. Object-Relational Mapping (ORM) is a technique that used to query and manipulate data from a SQLite database using an object-oriented paradigm. And Sugar ORM tak

Laravel 5.4 Bootstrap row class for every 3 columns

Sometimes you need to show three or four columns in a row using Laravel 5.4 and blade template engine. Here I show how to do it using chunk function in Laravel blade. As the first step let's get products from the database and pass it to the blade view. And let's check our blade file. In the following example,  @ foreach  takes the  $ products array and chuck it. In this example, I split it by three. You can pass any number according to your specification. And you will see the inner @ foreach loop through  $ items. If you have any question please comment it and I will try to solve it.

Mobile Backend As A Service (BaaS) platform for Android

Many mobile apps and games rely on a backend service for things that can’t be done solely on hosted device, such as sharing and processing data from multiple users, or storing large files. Backend as a service (BaaS) provides a centralised database and other features to manage user-generated data and application data. The developer can link applications to the backend service and backend service expose APIs to manage users, integrate push notification and analytics. BaaS is a recent development of cloud computing technology. Using backend services provide developers functionalities to manage users, data and to analyse real-time changes actively. Backend service should be able to handle the offline case gracefully and minimise battery drain. Back in the day developers had to develop custom backend platforms using server-side technologies. And developers had to scale up and down according to the user base and app usage. It was time-consuming in terms of resources and skills. Most mob