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.
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.
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
defp(i):# parent
return (i-1)//2
defl(i):# left child
return2*i+1
defr(i):# right child
return2*i+2
```
```python
definsert(x):
"""Append x to the end and bubble up"""
```
```python
defbubble_up(i):
whilei>0:
ifheap[i]<heap[p(i)]:
heap[i],heap[p(i)]=heap[p(i)],heap[i]
i=p(i)
else:
break
```
```python
defdelete_max():
"""Delete the maximum (root), put the last element