
CS245-2009S-10 Sorting 1
10-0: Main Memory Sorting
•All data elements can be stored in memory at the same time
•Data stored in an array, indexed from 0.. . n −1, where nis the number of elements
•Each element has a key value (accessed with a key() method)
•We can compare keys for ¡, ¿, =
•For illustration, we will use arrays of integers – though often keys will be strings, other Comparable types
10-1: Stable Sorting
•A sorting algorithm is Stable if the relative order of duplicates is preserved
•The order of duplicates matters if the keys are duplicated, but the records are not.
3 1 2 1 1 2 3
B
o
b
J
o
e
E
dA
m
y
S
u
e
A
lB
u
d
Key
Data
1 1 1 2 2 3 3
A
m
y
J
o
e
S
u
e
E
dA
lB
o
b
B
u
d
Key
Data
Anon-Stable sort
10-2: Insertion Sort
•Separate list into sorted portion, and unsorted portion
•Initially, sorted portion contains first element in the list, unsorted portion is the rest of the list
•(A list of one element is always sorted)
•Repeatedly insert an element from the unsorted list into the sorted list, until the list is sorted
10-3: Θ() For Insertion Sort
•Running time ∝# of comparisons
•Worst Case:
10-4: Θ() For Insertion Sort
•Running time ∝# of comparisons
•Worst Case: Inverse sorted list
# of comparisons:
10-5: Θ() For Insertion Sort
•Running time ∝# of comparisons