1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| def heapSort(arr): arr = builtHeap(arr) index = len(arr) - 1 while index > 0: swap(arr, index) index -= 1
return arr
def sink(arr, index): i1 = 0 while (2 * i1 + 1) < index: i2 = 2 * i1 + 1 if 2 * i1 + 2 < index: if arr[2 * i1 + 1] > arr[2 * i1 + 2]: i2 = 2 * i1 + 1 else: i2 = 2 * i1 + 2 if arr[i1] < arr[i2]: arr[i1], arr[i2] = arr[i2], arr[i1] i1 = i2 else: break
def swim(arr, index): while arr[index] > arr[max((index - 1) // 2, 0)]: arr[index], arr[(index - 1) // 2] = arr[(index - 1) // 2], arr[index] index = (index - 1) // 2
def swap(arr, index): arr[0], arr[index] = arr[index], arr[0] sink(arr, index)
def builtHeap(arr): length = len(arr) temp = [0] * length for i in range(len(arr)): temp[i] = arr[i] swim(temp, i)
return temp
if __name__ == '__main__': a = [59, 56, 97, 19, 40, 48, 13, 75, 51, 65] out = heapSort(a) print(out)
[out]: [13, 19, 40, 48, 51, 56, 59, 65, 75, 97]
|