Skip to main content

Python Binary Search

Here you will learn about python binary search with program and algorithm.

In linear search, we have to check each node/element. Because of this, time complexity increases. To reduce this time complexity, we use Binary search. In Binary search half of the given array will be ignored after just one comparison.

The main point to be noted is Binary Search only works for sorted array.

If the array is sorted into ascending order, all we have to do is find the middle index of the array and then compare the element at middle index with the element to find. If our given element is greater than the element at middle index then we’ll ignore the left half array and the array will start from the next index of middle index.

On other hand, if the given element is less than the element presents at middle index, then we’ll ignore the right half array and the new array will ends with left one index of middle index.

If the given element is equal to the element presents on the middle index, then search is completed.

In the case, the first index is greater than the last index of array, it means we have been gone through the entire array and the given element is not presented in the array.

Python Binary Search

Example:

We’ve a sorted array [2, 14, 19, 21, 99, 210, 512, 1028, 4443, 5110] and the element to be find is 4443.

Step 1:

python binary search 1

Step 2:

python binary search 2

Step 3:

python binary search 3

Step:4

python binary search 4

Algorithm:

Binary_search [arr, starting index, last index, element]
Step:1-  mid = (starting index + last index) / 2
Step:2-  If starting index > last index
                Then, Print "Element not found" 
                        Exit

         Else if element > arr[mid]
                   Then,  starting index = mid + 1
                   Go to Step:1
        
             Else if element < arr[mid]
                   Then, last index = mid -  1
                Go to Step:2
        
             Else:
                   { means element == arr[mid] }
                   Print "Element Presented at position" + mid
                   Exit

Program for Binary Search in Python

Iterative Approach (Using Loop):

def Binary_search(arr,start_index,last_index,element):
        while (start_index<= last_index):
                mid =(int)(start_index+last_index)/2
                if (element>arr[mid]):
                        start_index = mid+1
                elif (element<arr[mid]):
                        last_index = mid-1
                elif (element == arr[mid]):
                        return mid
        return -1
        
arr = [2,14,19,21,99,210,512,1028,4443,5110]
element = 4443
start_index = 0
last_index = len(arr)-1
found = Binary_search(arr,start_index,last_index,element)
if (found == -1):
        print "element not present in array"
else:
        print "element is present at index " + str(found)

Output

element is present at index 8

Recursive Approach (Using Recursion):

def Binary_search(arr,start_index,last_index,element):
        mid =(int)(start_index+last_index)/2

        if(start_index>last_index):
                print "Element not found"
        
        elif (element>arr[mid]):
                start_index = mid+1
                Binary_search(arr,start_index,last_index,element)

        elif (element<arr[mid]):
                last_index = mid-1
                Binary_search(arr,start_index,last_index,element)

        else:
                print "element is present at index " + str(mid)
        
arr = [2,14,19,21,99,210,512,1028,4443,5110]
element = 99
start_index = 0
last_index = len(arr)-1
Binary_search(arr,start_index,last_index,element)

Output

element is present at index 4

Comment below if you have any queries related to above python binary search algorithm tutorial.

The post Python Binary Search appeared first on The Crazy Programmer.



from The Crazy Programmer https://www.thecrazyprogrammer.com/2017/11/python-binary-search.html

Comments

Popular posts from this blog

Rail Fence Cipher Program in C and C++[Encryption & Decryption]

Here you will get rail fence cipher program in C and C++ for encryption and decryption. It is a kind of transposition cipher which is also known as zigzag cipher. Below is an example. Here Key = 3. For encryption we write the message diagonally in zigzag form in a matrix having total rows = key and total columns = message length. Then read the matrix row wise horizontally to get encrypted message. Rail Fence Cipher Program in C #include<stdio.h> #include<string.h> void encryptMsg(char msg[], int key){ int msgLen = strlen(msg), i, j, k = -1, row = 0, col = 0; char railMatrix[key][msgLen]; for(i = 0; i < key; ++i) for(j = 0; j < msgLen; ++j) railMatrix[i][j] = '\n'; for(i = 0; i < msgLen; ++i){ railMatrix[row][col++] = msg[i]; if(row == 0 || row == key-1) k= k * (-1); row = row + k; } printf("\nEncrypted Message: "); for(i = 0; i < key; ++i) f...

Data Encryption Standard (DES) Algorithm

Data Encryption Standard is a symmetric-key algorithm for the encrypting the data. It comes under block cipher algorithm which follows Feistel structure. Here is the block diagram of Data Encryption Standard. Fig1: DES Algorithm Block Diagram [Image Source: Cryptography and Network Security Principles and Practices 4 th Ed by William Stallings] Explanation for above diagram: Each character of plain text converted into binary format. Every time we take 64 bits from that and give as input to DES algorithm, then it processed through 16 rounds and then converted to cipher text. Initial Permutation: 64 bit plain text goes under initial permutation and then given to round 1. Since initial permutation step receiving 64 bits, it contains an 1×64 matrix which contains numbers from 1 to 64 but in shuffled order. After that, we arrange our original 64 bit text in the order mentioned in that matrix. [You can see the matrix in below code] After initial permutation, 64 bit text passed throug...

Experimental: Reducing the size of .NET Core applications with Mono's Linker

The .NET team has built a linker to reduce the size of .NET Core applications. It is built on top of the excellent and battle-tested mono linker . The Xamarin tools also use this linker so it makes sense to try it out and perhaps use it everywhere! "In trivial cases, the linker can reduce the size of applications by 50%. The size wins may be more favorable or more moderate for larger applications. The linker removes code in your application and dependent libraries that are not reached by any code paths. It is effectively an application-specific dead code analysis ." - Using the .NET IL Linker I recently updated a 15 year old .NET 1.1 application to cross-platform .NET Core 2.0 so I thought I'd try this experimental linker on it and see the results. The linker is a tool one can use to only ship the minimal possible IL code and metadata that a set of programs might require to run as opposed to the full libraries. It is used by the various Xamarin products to extract...