Bidirectional Bubble Sort with Early Exit and Shrinking Window
Heaps, Sorting & SearchAuto-graded · 24 test casesLast updated
Implement a two-direction adjacent-swap sort that returns a new sorted list, using window shrinking and early termination, while reasoning about its cost.
Write a function that sorts a list of integers in non-decreasing order using a bidirectional bubble sort (also called a shaker sort). It must return a new list and must not modify the input.
How the algorithm works
Keep a window [lo, hi] of positions that might still be out of order. Initially it covers the whole list. Repeat the following while lo < hi:
- Rightward sweep. Walk from
lotohi - 1. Whenever an element is strictly greater than its right neighbour, swap them. After the sweep, the largest value in the window sits athi, so decreasehiby 1. - Leftward sweep. Walk from
hidown tolo + 1. Whenever an element is strictly greater than the one on its left, swap the pair. After the sweep, the smallest value in the window sits atlo, so increaseloby 1.
Two optimizations are required:
- Shrinking window: positions outside
[lo, hi]are never examined again. - Early termination: if a sweep (in either direction) performs no swaps, the window is already ordered, so stop immediately. Check this after every sweep, not just once per round.
Input and output
- Input: a list of integers.
- Output: a new list with the same values in non-decreasing order.
Rules
- Swap only when two neighbours are strictly out of order, so equal values never change their relative order.
- The input list must remain unchanged.
- An empty list or a one-element list is returned as a copy.
Constraints
0 <= len(arr) <= 5000- Each value is an integer that fits in a 32-bit signed range.
- Duplicates and negative numbers may appear.
- Worst-case time of O(n^2) is acceptable; O(n) auxiliary space for the copy is acceptable.
Examples
Example 1
Input: bidirectional_bubble_sort([5, 1, 4, 2, 8])
Output: [1, 2, 4, 5, 8]
Example 2
Input: bidirectional_bubble_sort([3, 2, 1])
Output: [1, 2, 3]
Example 3
Input: bidirectional_bubble_sort([1, 2, 3, 4])
Output: [1, 2, 3, 4]
Example 4
Input: bidirectional_bubble_sort([4, 3, 3, -1, 0])
Output: [-1, 0, 3, 3, 4]
Hints
Hint 1
Work on a copy of the input so the caller's list is untouched, and track the window with two indices, lo and hi.
Hint 2
After a rightward sweep the window's maximum is in its final spot, so hi shrinks; after a leftward sweep the minimum is final, so lo grows.
Hint 3
Use a boolean flag per sweep: if no swap happened, break out right away, and do this check after each of the two sweeps.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Copy the input, then maintain a window [lo, hi] that may still contain unsorted elements.
- Sweep right from
lotohi, swapping adjacent pairs that are strictly out of order. This pushes the window's maximum tohi. If no swap occurred, stop. Otherwise decrementhi. - Sweep left from
hitolo, swapping adjacent pairs that are strictly out of order. This pulls the window's minimum tolo. If no swap occurred, stop. Otherwise incrementlo. - Repeat until the window has at most one element or an early exit triggers.
Why it is correct
At the start of each iteration, everything after hi consists of the largest elements in final order, everything before lo consists of the smallest elements in final order, and the window holds values lying between them.
- The rightward sweep carries the running maximum along, so it ends at
hi, which is its final position. Hencehican shrink. - The leftward sweep symmetrically settles the minimum at
lo. - A sweep with no swaps means every adjacent pair in the window is in order, so the window is sorted. Together with the settled ends, the whole list is sorted.
- Each round shrinks the window by 2, so the loop terminates, and when
lo >= hiat most one element remains, which is trivially in place.
Swapping only on strict > keeps equal elements in their original relative order (the sort is stable). Every adjacent swap removes exactly one inversion, so the total number of swaps equals the number of inversions.
Complexity
- Time: O(n^2) in the worst and average cases (reverse-sorted input gives n(n-1)/2 comparisons and swaps); O(n) in the best case (already sorted: one sweep of n-1 comparisons, then exit).
- Space: O(n) for the copy; the sorting itself uses O(1) extra space.
It beats a one-directional bubble sort on inputs with small values near the end (for example [2, 3, 4, 5, 1]), since the leftward sweep moves such a value all the way home in one pass.
Reference solution
from typing import List
def bidirectional_bubble_sort(arr: List[int]) -> List[int]:
values = arr.copy()
lo, hi = 0, len(values) - 1
while lo < hi:
swapped = False
for i in range(lo, hi):
if values[i] > values[i + 1]:
values[i], values[i + 1] = values[i + 1], values[i]
swapped = True
if not swapped:
break
hi -= 1
swapped = False
for i in range(hi, lo, -1):
if values[i - 1] > values[i]:
values[i - 1], values[i] = values[i], values[i - 1]
swapped = True
if not swapped:
break
lo += 1
return values