Python Program for Stooge Sort

In this article, we will learn about the Stooge Sort algorithm and implement it in Python. Stooge Sort is a recursive sorting algorithm that divides the array into overlapping parts and sorts them multiple times to ensure correctness.

Problem statement − We are given an array, we need to sort it using stooge sort.

Algorithm

The Stooge Sort algorithm follows these steps ?

1. Check if value at index 0 is greater than value at last index, then swap them.
2. Sort the initial 2/3rd of the array.
3. Sort the last 2/3rd of the array.
4. Sort the initial 2/3rd again to confirm.

How Stooge Sort Works

Stooge Sort Process Original: 4 2 3 1 Step 1: Swap ends if needed 1 2 3 4 Step 2-4: Recursive sorting First 2/3 Last 2/3

Python Implementation

Here's the complete implementation of Stooge Sort ?

def stoogesort(arr, l, h):
    if l >= h:
        return
    
    # swap if first element is greater than last
    if arr[l] > arr[h]:
        arr[l], arr[h] = arr[h], arr[l]
    
    # if there are more than 2 elements
    if h - l + 1 > 2:
        t = (h - l + 1) // 3
        
        # sort first 2/3 elements
        stoogesort(arr, l, h - t)
        
        # sort last 2/3 elements
        stoogesort(arr, l + t, h)
        
        # sort first 2/3 elements again
        stoogesort(arr, l, h - t)

# Example usage
numbers = [1, 4, 2, 3, 6, 5, 8, 7]
n = len(numbers)

print("Original array:", numbers)
stoogesort(numbers, 0, n - 1)
print("Sorted array:", numbers)
Original array: [1, 4, 2, 3, 6, 5, 8, 7]
Sorted array: [1, 2, 3, 4, 5, 6, 7, 8]

Time Complexity

Stooge Sort has a time complexity of O(n^2.7) which makes it inefficient for large datasets. The algorithm makes three recursive calls for every subarray, leading to this poor performance.

Key Points

  • Stooge Sort is a recursive sorting algorithm
  • It works by sorting overlapping 2/3 portions of the array
  • The algorithm ensures correctness by sorting the first 2/3 twice
  • It's mainly used for educational purposes due to its poor time complexity

Conclusion

Stooge Sort demonstrates an interesting recursive approach to sorting but is impractical for real-world use due to its O(n^2.7) time complexity. It's primarily valuable for understanding recursive algorithms and their complexity analysis.

Updated on: 2026-03-25T06:52:59+05:30

297 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements