From bccd6e1ee8a57fe0e55fd99fbb2adcb32ddc9be1 Mon Sep 17 00:00:00 2001 From: Nils Liebreich <nilsl99@mi.fu-berlin.de> Date: Wed, 24 May 2023 13:44:35 +0200 Subject: [PATCH] Lecture XII --- oop.md | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/oop.md b/oop.md index 6dbf86d..5ab6ab3 100644 --- a/oop.md +++ b/oop.md @@ -290,3 +290,61 @@ def quicksort(a, left=0, right=None): The speed of quicksort depends on the choice of the pivot element. If we choose the pivot element randomly the list will be split equally most of the time. If an algorithm uses randomness, is deterministic, but the runtime depends on the randomness, it's called Las-Vegas-Algorithm: "Las Vegas never cheats". This is in contrast to Monte-Carlo-Algorithms, where the result can be wrong but this is very unlikely. + +--- +*24.05.2023 Lecture `XII`* + +#### Data Structures +A data structureis a method to represent and structure data inside the computer, to provide certain functions. + +#### Heap Sort +The idea of Heap sort is to use a approapriate data structureto sort the list. We can use a priority queue, which has two methods: ++ `insert`: Insert an object into the correct slot ++ `delete_max`: Delete the object with the highest priority and returns it + +These methods can be implemented in many different ways. Heap Sort uses a very efficient implementationn, namely a binary max-heap. +A binary max-heap is an almost perfect binary tree where the maximum is inside the root. In a binary tree knot can have at most two children. In an almost perfect tree all layers except the last layer are completely filled and the last layer is filled from the left side. All childrens are smaller or equal to its parent in a max-heap. + +Binary Heaps can be implemented very efficiently as an array. The children and parents can be found by these simple equations: +```python +def p(i): # parent + return (i - 1) // 2 +def l(i): # left child + return 2 * i + 1 +def r(i): # right child + return 2 * i + 2 +``` + +```python +def insert(x): + """Append x to the end and bubble up""" +``` + +```python +def bubble_up(i): + while i > 0: + if heap[i] < heap[p(i)]: + heap[i], heap[p(i)] = heap[p(i)], heap[i] + i = p(i) + else: + break +``` + +```python +def delete_max(): + """Delete the maximum (root), put the last element + in the top (root) and bubble down.""" +``` + +```python +def bubble_down(i): + if l(i) >= size or heap[l(i)] >= heap[i] and r(i) >= size or heap[r(i)] >= heap[i]: + return + else: + if heap[l(i)] < heap[r(i)] or r(i) >= size: + heap[i], heap[l(i)] = heap[l(i)], heap[i] + bubble_down(l(i)) + else: + heap[i], heap[r(i)] = heap[r(i)], heap[i] + bubble_down(r(i)) +``` -- GitLab