From d653d3598d71fea30d45d118e3d046a3aed53ac1 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Thu, 27 Jun 2024 22:39:22 +0200 Subject: Uncommented test files --- progs/a339.py | 52 ++++++++++++++++++++++++++-------------------------- 1 file changed, 26 insertions(+), 26 deletions(-) (limited to 'progs/a339.py') diff --git a/progs/a339.py b/progs/a339.py index 95724d2..53fcb7e 100644 --- a/progs/a339.py +++ b/progs/a339.py @@ -1,28 +1,28 @@ -# FIXME: chiamata a funzione definita dopo -# -# def heap_sort(arr): -# heapify(arr) -# end = len(arr) - 1 -# while end > 0: -# arr[end], arr[0] = arr[0], arr[end] -# shift_down(arr, 0, end - 1) -# end -= 1 -# return arr +def heap_sort(arr): + heapify(arr) + end = len(arr) - 1 + while end > 0: + arr[end], arr[0] = arr[0], arr[end] + shift_down(arr, 0, end - 1) + end -= 1 + return arr -# def heapify(arr): -# start = len(arr) // 2 -# while start >= 0: -# shift_down(arr, start, len(arr) - 1) -# start -= 1 -# def shift_down(arr, start, end): -# root = start -# while root * 2 + 1 <= end: -# child = root * 2 + 1 -# if child + 1 <= end and arr[child] < arr[child + 1]: -# child += 1 -# if child <= end and arr[root] < arr[child]: -# arr[root], arr[child] = arr[child], arr[root] -# root = child -# else: -# return +def heapify(arr): + start = len(arr) // 2 + while start >= 0: + shift_down(arr, start, len(arr) - 1) + start -= 1 + + +def shift_down(arr, start, end): + root = start + while root * 2 + 1 <= end: + child = root * 2 + 1 + if child + 1 <= end and arr[child] < arr[child + 1]: + child += 1 + if child <= end and arr[root] < arr[child]: + arr[root], arr[child] = arr[child], arr[root] + root = child + else: + return -- cgit v1.2.3-18-g5258