|
| 1 | +def merge_sort(array, update_callback): |
| 2 | + def merge_sort_recursive(arr, temp, left_start, right_end): |
| 3 | + if left_start >= right_end: |
| 4 | + return |
| 5 | + |
| 6 | + middle = (left_start + right_end) // 2 |
| 7 | + merge_sort_recursive(arr, temp, left_start, middle) |
| 8 | + merge_sort_recursive(arr, temp, middle + 1, right_end) |
| 9 | + merge(arr, temp, left_start, right_end) |
| 10 | + |
| 11 | + def merge(arr, temp, left_start, right_end): |
| 12 | + left_end = (right_end + left_start) // 2 |
| 13 | + right_start = left_end + 1 |
| 14 | + size = right_end - left_start + 1 |
| 15 | + |
| 16 | + left = left_start |
| 17 | + right = right_start |
| 18 | + index = left_start |
| 19 | + |
| 20 | + highlight = list(range(left_start, right_end + 1)) |
| 21 | + |
| 22 | + while left <= left_end and right <= right_end: |
| 23 | + # Highlight elements being compared |
| 24 | + update_callback(arr, highlight_indices=[left, right], moving_index=index) |
| 25 | + if arr[left] <= arr[right]: |
| 26 | + temp[index] = arr[left] |
| 27 | + left += 1 |
| 28 | + else: |
| 29 | + temp[index] = arr[right] |
| 30 | + right += 1 |
| 31 | + index += 1 |
| 32 | + |
| 33 | + # Copy remaining elements from left half |
| 34 | + while left <= left_end: |
| 35 | + update_callback(arr, highlight_indices=[left], moving_index=index) |
| 36 | + temp[index] = arr[left] |
| 37 | + left += 1 |
| 38 | + index += 1 |
| 39 | + |
| 40 | + # Copy remaining elements from right half |
| 41 | + while right <= right_end: |
| 42 | + update_callback(arr, highlight_indices=[right], moving_index=index) |
| 43 | + temp[index] = arr[right] |
| 44 | + right += 1 |
| 45 | + index += 1 |
| 46 | + |
| 47 | + # Copy sorted elements back to original array |
| 48 | + for i in range(left_start, right_end + 1): |
| 49 | + arr[i] = temp[i] |
| 50 | + # Show the placement in the original array |
| 51 | + update_callback(arr, highlight_indices=[i], moving_index=i) |
| 52 | + |
| 53 | + n = len(array) |
| 54 | + temp_array = [0] * n |
| 55 | + merge_sort_recursive(array, temp_array, 0, n - 1) |
| 56 | + |
| 57 | + update_callback(array) # Final update before sweep |
| 58 | + |
| 59 | + # Final sweep animation |
| 60 | + for i in range(n): |
| 61 | + update_callback(array, moving_index=i, end=True, sweep=True) |
0 commit comments