From 1caa1a69a023dca8ecb79e62c023b4b98134d81f Mon Sep 17 00:00:00 2001
From: Nils Liebreich <nilsl99@zedat.fu-berlin.de>
Date: Wed, 2 Nov 2022 13:46:54 +0100
Subject: [PATCH] Implemented HeapSort

---
 Aufgabe02.py | 47 +++++++++++++++++++++++++++++++++++++++++------
 1 file changed, 41 insertions(+), 6 deletions(-)

diff --git a/Aufgabe02.py b/Aufgabe02.py
index 7ed0758..a909e10 100644
--- a/Aufgabe02.py
+++ b/Aufgabe02.py
@@ -1,8 +1,8 @@
 def HeapSort(array):
     '''Update the board according to the move and the player. If player 0 does
-    the move, set the board cell to -1. If payer 1 makes the move, set the board cell 
+    the move, set the board cell to -1. If payer 1 makes the move, set the board cell
     to 1 (empty board cells have value zero).
-    
+
     Parameters
     ----------
     array: list(*int)
@@ -13,11 +13,46 @@ def HeapSort(array):
     sorted_array: a sorted copy of the array
     '''
 
-    return
+    p = lambda i: (i-1)//2
+    l = lambda i: 2*i + 1
+    r = lambda i: 2*i + 2
+
+    sorted_array = list(array)
+
+    # Erzeuge einen max-Heap
+    for i in range(1, len(sorted_array)):
+        j = i
+        while sorted_array[j] > sorted_array[p(j)] and j != 0:
+            sorted_array[j], sorted_array[p(j)] = sorted_array[p(j)], sorted_array[j]
+            j = p(j)
+
+    # Entferne max aus dem max-Heap
+    for i in range(len(sorted_array)-1, 1, -1):
+        sorted_array[0], sorted_array[i] = sorted_array[i], sorted_array[0]
+        j = 0
+        while True:
+            if l(j) >= i or r(j) >= i:
+                break
+
+            if r(j) >= i and sorted_array[l(j)] > sorted_array[j]:
+                sorted_array[j], sorted_array[l(j)] = sorted_array[l(j)], sorted_array[j]
+                j = l(j)
+
+            if sorted_array[j] >= sorted_array[l(j)] and sorted_array[j] >= sorted_array[r(j)]:
+                break
+
+            if sorted_array[l(j)] > sorted_array[r(j)]:
+                sorted_array[j], sorted_array[l(j)] = sorted_array[l(j)], sorted_array[j]
+                j = l(j)
+            else:
+                sorted_array[j], sorted_array[r(j)] = sorted_array[r(j)], sorted_array[j]
+                j = r(j)
+
+    return sorted_array
 
 def InsertionSort(array):
     '''Sort the array by inserting each element into an already sorted part of the array.
-    
+
     Parameters
     ----------
     array: list(*int)
@@ -40,8 +75,8 @@ def InsertionSort(array):
     return sorted_array
 
 def CountingSort(array):
-    '''Sort the array by counting the occurrence of each element in the array.
-    
+    '''Sort the array by counting the ocjence of each element in the array.
+
     Parameters
     ----------
     array: list(*int)
-- 
GitLab