2019-02-28 in class

This commit is contained in:
Claudio Maggioni 2019-02-28 13:29:34 +01:00
parent 57a4615e08
commit fd7713fb33
2 changed files with 40 additions and 2 deletions

23
insertion_sort.py Executable file
View file

@ -0,0 +1,23 @@
#!/usr/bin/env python3
import sys
def insertionsort(A):
# start with the first and the second
# insert the next element in the right place in the first elements
# continue until the array is done
for j in range(1,len(A)):
print(A)
print(A)
i = j - 1
tomove = A[j]
while i >= 0 and tomove < A[i]:
if A[i] > A[i+1]:
# Swap A[i] and A[j]
A[i+1], A[i] = A[i], A[i+1]
i = i - 1
return A
args = [int(x) for x in sys.argv[1:]]
print(insertionsort(args))

View file

@ -70,8 +70,8 @@ o(g(n)) is the family of functions O(g(n)) excluding all the functions in
theta(g(n))
## Small omega notation
omega(g(n)) is the family of functions Omega(g(n)) excluding all the functions in
theta(g(n))
omega(g(n)) is the family of functions Omega(g(n)) excluding all the functions
in theta(g(n))
## Recap
*asymptotically* = <=> theta(g(n))
@ -79,3 +79,18 @@ theta(g(n))
*asymptotically* > <=> omega(g(n))
*asymptotically* <= <=> O(g(n))
*asymptotically* >= <=> Omega(g(n))
# Insertion sort
## Complexity
- *Best case:* Linear (theta(n))
- *Worst case:* Number of swaps = 1 + 2 + ... + n-1 = (n-1)n/2 = theta(n^2)
- *Average case:* Number of swaps half of worst case = n(n-1)/4 = theta(n^2)
## Correctness
Proof sort of by induction.
An algorithm is correct if given an input the output satisfies the conditions
stated. The algorithm must terminate.