From fd7713fb33b3e28a2ca0b23206bae684c0c5edde Mon Sep 17 00:00:00 2001 From: Claudio Maggioni Date: Thu, 28 Feb 2019 13:29:34 +0100 Subject: [PATCH] 2019-02-28 in class --- insertion_sort.py | 23 +++++++++++++++++++++++ notes.md | 19 +++++++++++++++++-- 2 files changed, 40 insertions(+), 2 deletions(-) create mode 100755 insertion_sort.py diff --git a/insertion_sort.py b/insertion_sort.py new file mode 100755 index 0000000..f369757 --- /dev/null +++ b/insertion_sort.py @@ -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)) diff --git a/notes.md b/notes.md index f48e18e..12b98ac 100644 --- a/notes.md +++ b/notes.md @@ -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.