Next: Chapter 9: Graph Algorithms
Up: CS 3345: Algorithm Analysis
Previous: Chapter 6: Priority Queues
Sorting
Goal: Sort a set of n elements.
Assumption: No element is repeated.
Insertion Sort
- (n-1) passes
- before pass P: elements 1 to P-1 are sorted
- in pass P: move Pth element left until
correct
place found
- after pass P: elements 1 to P are sorted
- Time complexity =
Shellsort
- use increment sequence ht,
h2, h1 in that
order
-
hk > hk-1, h1=1
- after hk phase, all elements hk apart are sorted
- hk-sort = insertion sort on hk independent sub-arrays
- worst case running time using Shell's
increments =
- Hibbard's increments =
- worst case running time with Hibbard's
increments =
Heapsort
- Build_Heap: O(n) time
- n Delete_Min operations:
- Time complexity =
O(n log n)
Mergesort
- Recursively:
- sort [
]
and [
]
- Merge sorted sub-lists
-
T(n) = 2T(n/2) + n
- T(1) = 1
- Therefore,
T(n) = O(n log n)
Quicksort
Recursive Solution: Quicksort(S)
- 1.
- pick any element v as pivot
- 2.
- partition
- 3.
- return {Quicksort(S1,), v, Quicksort(S2)}
Base Case: if
,
or 1, return {S}
- subproblems may not be of equal size
- partitioning can be performed in place and efficiently
Picking the pivot
- choosing first element as pivot
inefficient for presorted
or partially sorted input
- random choice of pivot: acceptable
- median of left, right and center elements
eliminates the
bad case of sorted input.
Quicksort: Time Complexity
T(n) = T(i) + T(n-i-1) + cn
T(0) = 1
- Worst Case:
- pivot is always the smallest
element
T(n) = O(n2) - Best Case:
- equal partitions
T(n) = 2 T(n/2) + cn
T(n) = O(n log n) - Average Case:
- each size of S1 is equally likely
T(n) = O(n log n)
Quickselect(S1, k)
Select kth smallest element from S
- 1.
- pick pivot
- 2.
- partition
into S1 and S2
- 3.
- if
,
Quickselect(S1, k)
- 4.
- if
,
return(pivot)
- 5.
- otherwise, Quickselect(S2,
)
- Quickselect makes only one recursive call (not two)
- worst case = O(n2)
- average case = O(n)
Sorting Large Objects
- swapping large objects is expensive
- swap pointers to objects, instead
- indirect sorting
External Sorting
- main memory is directly addressable
- secondary memory is not
- e.g., tape = sequential access
- non-sequential data access
increased execution time
- alleviate problem by using additional tapes
Next: Chapter 9: Graph Algorithms
Up: CS 3345: Algorithm Analysis
Previous: Chapter 6: Priority Queues
Ravi Prakash
1999-11-17