Python Program for Binary Insertion Sort

Binary insertion sort is an improved version of the regular insertion sort algorithm. In normal insertion sort, each element is compared linearly with the sorted portion to find its correct position, taking O(n) comparisons per element.

Binary insertion sort uses binary search to find the correct insertion position, reducing comparisons from O(n) to O(log n) per element. However, shifting elements still requires O(n) time in the worst case.

How Binary Insertion Sort Works

The algorithm combines binary search with insertion sort ?

  • Start from the second element (index 1)
  • Use binary search on the sorted left portion to find insertion position
  • Shift all greater elements to the right
  • Insert the current element at the found position

Binary Search Helper Function

First, we need a binary search function to find the correct insertion index ?

def binary_search(arr, val, start, end):
    """Find the insertion index using binary search"""
    while start <= end:
        mid = (start + end) // 2
        if arr[mid] < val:
            start = mid + 1
        else:
            end = mid - 1
    return start

# Test the binary search function
numbers = [1, 3, 5, 7, 9]
insert_pos = binary_search(numbers, 6, 0, len(numbers) - 1)
print(f"Insert 6 at index: {insert_pos}")
Insert 6 at index: 3

Complete Binary Insertion Sort Implementation

Now we implement the complete sorting algorithm ?

def binary_search(arr, val, start, end):
    """Find the insertion index using binary search"""
    while start <= end:
        mid = (start + end) // 2
        if arr[mid] < val:
            start = mid + 1
        else:
            end = mid - 1
    return start

def binary_insertion_sort(arr):
    """Sort array using binary insertion sort"""
    for i in range(1, len(arr)):
        key = arr[i]
        # Find insertion 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]
        # Insert element at correct position
        arr[index] = key
    return arr

# Example usage
numbers = [37, 23, 0, 17, 12, 72, 31]
print(f"Original: {numbers}")
sorted_numbers = binary_insertion_sort(numbers.copy())
print(f"Sorted: {sorted_numbers}")
Original: [37, 23, 0, 17, 12, 72, 31]
Sorted: [0, 12, 17, 23, 31, 37, 72]

Step-by-Step Example

Let's trace through the sorting process with a smaller array ?

def binary_insertion_sort_verbose(arr):
    """Binary insertion sort with step-by-step output"""
    print(f"Initial array: {arr}")
    
    for i in range(1, len(arr)):
        key = arr[i]
        print(f"\nStep {i}: Inserting {key}")
        
        # Find insertion position
        index = binary_search(arr, key, 0, i - 1)
        print(f"  Insertion position: {index}")
        
        # Shift and insert
        for j in range(i, index, -1):
            arr[j] = arr[j - 1]
        arr[index] = key
        
        print(f"  Array after insertion: {arr}")
    
    return arr

# Trace through example
data = [64, 34, 25, 12]
binary_insertion_sort_verbose(data)
Initial array: [64, 34, 25, 12]

Step 1: Inserting 34
  Insertion position: 0
  Array after insertion: [34, 64, 25, 12]

Step 2: Inserting 25
  Insertion position: 0
  Array after insertion: [25, 34, 64, 12]

Step 3: Inserting 12
  Insertion position: 0
  Array after insertion: [12, 25, 34, 64]

Time and Space Complexity

Complexity Regular Insertion Sort Binary Insertion Sort
Comparisons O(n²) O(n log n)
Shifts O(n²) O(n²)
Overall Time O(n²) O(n²)
Space O(1) O(1)

Conclusion

Binary insertion sort reduces comparison operations from O(n²) to O(n log n) using binary search. However, the overall time complexity remains O(n²) due to element shifting operations. It's most useful when comparison operations are expensive relative to data movement.

Updated on: 2026-03-25T06:49:09+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements