def calculate_min_run(n): r = 0 while n >= 32: r |= n & 1 n >>= 1 return n + r def insertion_sort(arr, left, right): # Function to perform insertion sort on a given portion of the array for i in range(left + 1, right + 1): j = i while j > left and arr[j] < arr[j - 1]: arr[j], arr[j - 1] = arr[j - 1], arr[j] j -= 1 def merge(arr, l, m, r): # Function to merge two halves of the array len1, len2 = m - l + 1, r - m left, right = [], [] # Create temporary left and right arrays for i in range(0, len1): left.append(arr[l + i]) for i in range(0, len2): right.append(arr[m + 1 + i]) i, j, k = 0, 0, l while i < len1 and j < len2: # Merge the two halves back into the original array if left[i] <= right[j]: arr[k] = left[i] i += 1 else: arr[k] = right[j] j += 1 k += 1 while i < len1: arr[k] = left[i] k += 1 i += 1 while j < len2: arr[k] = right[j] k += 1 j += 1 def tim_sort(arr): n = len(arr) min_run = calculate_min_run(n) # Perform insertion sort on small chunks for start in range(0, n, min_run): end = min(start + min_run - 1, n - 1) insertion_sort(arr, start, end) size = min_run while size < n: # Merge the sorted chunks for left in range(0, n, 2 * size): mid = min(n - 1, left + size - 1) right = min((left + 2 * size - 1), (n - 1)) if mid < right: merge(arr, left, mid, right) size = 2 * size # Test the tim_sort function with a sample array tim_sort([1, 2, 3])
- def calculate_min_run(n):
- r = 0
- while n >= 32:
- r |= n & 1
- n >>= 1
- return n + r
- def insertion_sort(arr, left, right):
- # Function to perform insertion sort on a given portion of the array
- for i in range(left + 1, right + 1):
- j = i
- while j > left and arr[j] < arr[j - 1]:
- arr[j], arr[j - 1] = arr[j - 1], arr[j]
- j -= 1
- def merge(arr, l, m, r):
- # Function to merge two halves of the array
- len1, len2 = m - l + 1, r - m
- left, right = [], []
- # Create temporary left and right arrays
- for i in range(0, len1):
- left.append(arr[l + i])
- for i in range(0, len2):
- right.append(arr[m + 1 + i])
- i, j, k = 0, 0, l
- while i < len1 and j < len2:
- # Merge the two halves back into the original array
- if left[i] <= right[j]:
- arr[k] = left[i]
- i += 1
- else:
- arr[k] = right[j]
- j += 1
- k += 1
- while i < len1:
- arr[k] = left[i]
- k += 1
- i += 1
- while j < len2:
- arr[k] = right[j]
- k += 1
- j += 1
- def tim_sort(arr):
- n = len(arr)
- min_run = calculate_min_run(n)
- # Perform insertion sort on small chunks
- for start in range(0, n, min_run):
- end = min(start + min_run - 1, n - 1)
- insertion_sort(arr, start, end)
- size = min_run
- while size < n:
- # Merge the sorted chunks
- for left in range(0, n, 2 * size):
- mid = min(n - 1, left + size - 1)
- right = min((left + 2 * size - 1), (n - 1))
- if mid < right:
- merge(arr, left, mid, right)
- size = 2 * size
tim_sort([1, 2, 3])- # Test the tim_sort function with a sample array
- tim_sort([1, 2, 3])