KatInterview

Bidirectional Bubble Sort with Early Exit and Shrinking Window

Heaps, Sorting & SearchAuto-graded · 24 test cases
MediumAuto-gradedHeaps, Sorting & Searchsortingtwo-pointersbubble-sort

Last 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:

  1. Rightward sweep. Walk from lo to hi - 1. Whenever an element is strictly greater than its right neighbour, swap them. After the sweep, the largest value in the window sits at hi, so decrease hi by 1.
  2. Leftward sweep. Walk from hi down to lo + 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 at lo, so increase lo by 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.