Lecture 3

Recap Lecture 2

Quick-sort

Quick sort recursion tree

Alt text

The worst case running time

Expected running time

Probabilistic fact: Expected number of coin tosses required in order to get kk heads is 2k2k

In practise, quick sort is chosen over merge sort:

Sorting:

def bogo_sort(my_list): while is_sorted(my_list) == False: random_shuffle(my_list)

worst case: unbounded

Average case: nn!n \cdot n!

Best case: nn

Lecture 3

Counting Comparisons

E.g. permutations

<a,b,c>=c=3 <a, b, c> = |c| = 3

permutation
a, b, c,
a, c, b
b, a, c
b, c, a
c, a, b,
c, b, a

Every comparison based sort takes at best nlognn \log n time

Alt text

Lower Bound

Bucket sort

Alt text

Algorithm bucketSort(S): Input: sequence S of n entries with integer keys in the range [0, N − 1] Output: sequence S sorted in nondecreasing order of the keys B ← array of N empty sequences for each entry e in S do k ← key of e remove e from S insert e at the end of bucket B[k] for i ← 0 to N−1 do for each entry e in B[i] do remove e from B[i] insert e at the end of S

Analysis (algorithm above)

Properties and Extensions

Lexicographic order:

Lexicographic-sort (Tuple sort)

Algorithm lexicographicSort(S) Input sequence S of d-tuples Output sequence S sorted in lexicographic order for i <- d downto 1 stableSort(S, Ci)

Radix sort

Radix-sort for binary numbers

Example

Alt text

Memory usage

Radix Sort: (converting to binary)

Arrays

A linear structure is one whose elements can be seen as being in a sequence. That is, one element follows the next.

Static sequence ADT

ADT for a sequence: given a list of items XX in some order:

Dynamic Sequence ADT

Array implementation efficiency:

Singly linked list

linked list

Simple process to insert between two elements

Singly linked list

Alt text

Doubly linked list

Alt text

Circularly Linked list

Alt text

Extensible lists

Linked list implementation efficiency

Note: Augmentation

class LinkedList: def __init__(self): self.__head = None self.__tail = None self.__size = 0

ExtensibleLists

Insertion

Removal

Alt text

Performance

Extensible lists

Comparison of Strategies

Incremental strategy analysis

Doubling strategy analysis