
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program for Binary Insertion Sort
Binary Insertion Sort
Binary insertion sort is an improved version of the regular Insertion Sort algorithm. In a normal insertion sort, each element is compared linearly with the sorted portion of the list to find its correct position. This takes O(n) comparisons for each element.
In Binary Insertion Sort, we use Binary Search to find the correct position of the current element in the sorted part of the list. This reduces the number of comparisons from O(n) to O(log n) per insertion. However, shifting elements still takes O(n) time in the worst case.
Problem Statement
You are given a list of unsorted numbers. Your task is to sort the list using Binary Insertion Sort, where each element is inserted at its correct position using Binary Search.
Binary Search-Based Insertion
We use a helper function that applies binary search to find the correct index where the current element should be inserted in the sorted sublist. Once the index is found, we shift elements and insert the current element in that position.
Steps for Binary Insertion Sort
- Iterate from index 1 to the end of the list.
- Use Binary Search on the left (sorted) portion of the list to find the insertion index.
- Shift all greater elements to the right.
- Insert the element at the found index.
Python Program for Binary Insertion Sort
In this example, we first define a binary search function to find the correct index and then sort the list using binary insertion -
# Binary Search to find the insertion index def binary_search(arr, val, start, end): while start <= end: mid = (start + end) // 2 if arr[mid] < val: start = mid + 1 else: end = mid - 1 return start # Function to perform Binary Insertion Sort def binary_insertion_sort(arr): for i in range(1, len(arr)): key = arr[i] # Find index using binary search index = binary_search(arr, key, 0, i - 1) # Shift elements to make space for j in range(i, index, -1): arr[j] = arr[j - 1] arr[index] = key return arr # Test input arr = [37, 23, 0, 17, 12, 72, 31] sorted_arr = binary_insertion_sort(arr) print(sorted_arr)
Following is the output obtained -
[0, 12, 17, 23, 31, 37, 72]
All the variables are updated at each iteration to reflect the partial sorting of the array.