Created
September 6, 2023 09:36
-
-
Save theabbie/442bbbfbb7da88131c2abba8c73e19f6 to your computer and use it in GitHub Desktop.
Iterative Merge Sort in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def merge(arr, i, mid, j, extra): | |
x = i | |
y = mid | |
while x < mid and y < j: | |
if arr[x] <= arr[y]: | |
extra[x + y - mid] = arr[x] | |
x += 1 | |
else: | |
extra[x + y - mid] = arr[y] | |
y += 1 | |
extra[x + y - mid : y] = arr[x : mid] | |
extra[y : j] = arr[y : j] | |
arr[i : j] = extra[i : j] | |
def sort(arr): | |
n = len(arr) | |
k = len("{:0b}".format(n)) | |
pad = pow(2, k) - n | |
arr.extend([float('inf')] * pad) | |
extra = [0] * (n + pad) | |
l = 1 | |
for _ in range(k): | |
for i in range(0, n + pad, 2 * l): | |
merge(arr, i, i + l, i + 2 * l, extra) | |
l *= 2 | |
del arr[-pad:] | |
arr = [5, 4, 3, 2, 1] | |
sort(arr) | |
print(arr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment