insert(e)
operationsremoveMin()
operationsS
in two disjoint subsets S_1
and S_2
S_1
and S_2
S_1
and S_2
into a solution for S
0
or 1
O(n log n)
running timeIt accesses data in a sequential manner (suitable to sort data on a disk)
S
with n
elements consists of three steps:
S
into two sequences S_1
and S_2
of about n/2
elements eachS_1
and S_2
S_1
and S_2
into a unique sorted sequenceAlgorithm mergeSort(S, C)
Input sequence S with n
elements, comparator C
Output sequence S sorted
according to C
if S.size() > 1
(S1, S2) ← partition(S, n/2)
mergeSort(S1, C)
mergeSort(S2, C)
else:
S ← merge(S1, S2)
A
and B
into a sorted sequence S
containing the union of the elements of A
and B
n/2
elements and implemented by means of a doubly linked list, takes O(n)
timeAlgorithm merge(A, B)
Input sequences A and B with n/2 elements each
Output sorted sequence of A È B
S ← empty sequence
while (not A.empty()) and (not B.empty())
if A.front() < B.front()
S.addBack(A.front());
A.eraseFront();
else
S.addBack(B.front());
B.eraseFront();
while not A.empty()
S.addBack(A.front());
A.eraseFront();
while not B.empty()
S.addBack(B.front());
B.eraseFront();
return S
0
or 1
h
of the merge-sort tree is O(logn)
i
is O(n)
2^i
sequences of size n/2^i
2^(i+1)
recursive callsO(nlogn)
x
(called pivot) and partition S
into
L
elements less than x
E
elements equal x
G
elements greater than x
L
and G
L
, E
and G
y
from S
andy
into L
, E
or G
, depending on the result of the comparison with the pivot x
O(1)
timeO(n)
timeAlgorithm partition(S, p)
Input sequence S, position p of pivot
Output subsequences L, E, G of the elements of S less than, equal to, or greater than the pivot, respectively
L, E, G ← empty sequences
x ← S.erase(p)
while not S.empty()
y ← S.eraseFront()
if y < x
L.insertBack(y)
else if y = x
E.insertBack(y)
else // y > x
G.insertBack(y)
return L, E, G
0
or 1
L
and G
has size n-1
and the other has size 0
n + (n - 1) + ... + 2 + 1
O(n^2)
L
and G
are each less than 3s/4
L
and G
has size greater than 3s/4
A call is good with probability 1/2
1/2
of the possible pivots cause good calls:
O(logn)
O(n)
O(nlogn)
h
k
k
h
k
Algorithm inPlaceQuickSort(S, l, r)
Input sequence S, ranks l and r
Output sequence S with the elements of rank between l and r rearranged in increasing order
if l >= r
return
i ← a random integer between l and r
x ← S.elemAtRank(i)
(h, k) ← inPlacePartition(x)
inPlaceQuickSort(S, l, h - 1)
inPlaceQuickSort(S, k + 1, r)
Send pivot to the end of the sequence
l
and r
cross:
l
to the right until finding an element>=x
r
to the left until finding an element<x
l
and r
l
and at the end (at x
)