mirror of
https://hub.njuu.cf/TheAlgorithms/Python.git
synced 2023-10-11 13:06:12 +08:00
72f52df420
In this enhanced version: The function and variable names have been kept meaningful for readability. Comments have been added for clarity. The logic remains the same, but some variable names have been shortened to reduce line length. The function and input processing code is unchanged for user-friendliness.
42 lines
970 B
Python
42 lines
970 B
Python
def heapify(arr, n, i):
|
|
largest = i
|
|
left = 2 * i + 1
|
|
right = 2 * i + 2
|
|
|
|
if left < n and arr[left] > arr[largest]:
|
|
largest = left
|
|
|
|
if right < n and arr[right] > arr[largest]:
|
|
largest = right
|
|
|
|
if largest != i:
|
|
arr[i], arr[largest] = arr[largest], arr[i]
|
|
heapify(arr, n, largest)
|
|
|
|
|
|
def heap_sort(arr):
|
|
"""
|
|
Sorts a list using the heap sort algorithm.
|
|
:param arr: List of comparable items.
|
|
:return: Sorted list.
|
|
"""
|
|
n = len(arr)
|
|
|
|
# Build a max heap.
|
|
for i in range(n // 2 - 1, -1, -1):
|
|
heapify(arr, n, i)
|
|
|
|
# Extract elements one by one.
|
|
for i in range(n - 1, 0, -1):
|
|
arr[0], arr[i] = arr[i], arr[0]
|
|
heapify(arr, i, 0)
|
|
|
|
return arr
|
|
|
|
|
|
if __name__ == "__main__":
|
|
user_input = input("Enter numbers separated by a comma:\n").strip()
|
|
unsorted = [int(item) for item in user_input.split(",")]
|
|
sorted_arr = heap_sort(unsorted)
|
|
print(sorted_arr)
|