Start with the first number in a new "sorted pile".
Pick a random number from the remaining unsorted pile -- this is the Fredy twist.
Use binary search on the sorted pile to find where it belongs -- cut the pile in half, check the middle, repeat until the exact spot is found.
Insert it there. Shift everything else to make room.
Repeat until the unsorted pile is empty.
Complexity
Overall
O(n2)
Dominated by shifting elements to make room during insert.
Comparisons
O(n log n)
Binary search makes finding the right spot very efficient.
Best case
O(n log n)
When numbers happen to already be in order.
Randomness
Unpredictable
No "evil" input can force worst-case -- the order is always random.
Python code
import random
deffredy_sort(arr):
arr = arr.copy()
unsorted = arr[1:]
sorted_part = [arr[0]]
while unsorted:
# pick a random element
rand_idx = random.randint(0, len(unsorted) - 1)
current = unsorted.pop(rand_idx)
# binary search for the right spot
lo, hi = 0, len(sorted_part)
while lo < hi:
mid = (lo + hi) // 2if sorted_part[mid] < current:
lo = mid + 1else:
hi = mid
# insert it
sorted_part.insert(lo, current)
return sorted_part