|
| 1 | +import heapq |
| 2 | +import random |
| 3 | +""" |
| 4 | + KKirkpatrick-Reisch sorting algorithm. |
| 5 | + Divides input into sqrt(n) blocks, sorts each, then merges using a min-heap. |
| 6 | + |
| 7 | + Time Complexity: |
| 8 | + - Average case: O(n * sqrt(n)) |
| 9 | + - Worst case: O(n * sqrt(n)) |
| 10 | + - Best case: O(n * sqrt(n)) |
| 11 | +
|
| 12 | + Space Complexity: O(n) |
| 13 | + |
| 14 | +""" |
| 15 | + |
| 16 | +def kirkpatrick_reisch_sort(arr): |
| 17 | + n = len(arr) |
| 18 | + if n <= 1: |
| 19 | + return arr |
| 20 | + |
| 21 | + # Step 1: Divide the input into sqrt(n) blocks |
| 22 | + block_size = int(n ** 0.5) |
| 23 | + blocks = [arr[i:i + block_size] for i in range(0, n, block_size)] |
| 24 | + |
| 25 | + # Step 2: Sort each block |
| 26 | + for block in blocks: |
| 27 | + block.sort() |
| 28 | + |
| 29 | + # Step 3: Create a min-heap of the first elements of each block |
| 30 | + heap = [(block[0], i, 0) for i, block in enumerate(blocks) if block] |
| 31 | + heapq.heapify(heap) |
| 32 | + |
| 33 | + # Step 4: Extract elements from the heap and refill from blocks |
| 34 | + sorted_arr = [] |
| 35 | + while heap: |
| 36 | + val, block_index, element_index = heapq.heappop(heap) |
| 37 | + sorted_arr.append(val) |
| 38 | + |
| 39 | + if element_index + 1 < len(blocks[block_index]): |
| 40 | + next_element = blocks[block_index][element_index + 1] |
| 41 | + heapq.heappush(heap, (next_element, block_index, element_index + 1)) |
| 42 | + |
| 43 | + return sorted_arr |
| 44 | + |
| 45 | + |
| 46 | +if __name__ == '__main__': |
| 47 | + # Generate a random list of integers |
| 48 | + arr = [random.randint(1, 1000) for _ in range(100)] |
| 49 | + |
| 50 | + print("Original Array:", arr) |
| 51 | + sorted_arr = kirkpatrick_reisch_sort(arr) |
| 52 | + print("Sorted Array:", sorted_arr) |
| 53 | + |
| 54 | + # Verify the result |
| 55 | + assert (sorted_arr == sorted(arr)) |
0 commit comments