Lec 05 Elementary Sorting
Lec 05 Elementary Sorting
2
Sorting algorithms
Insertion sort :
in place: only a constant number of elements of the
input array are ever sorted outside the array.
Merge sort :
not in place.
Other elementary sorting methods:
selection sort, bubble sort, etc.
Heap sort : (Chapter 6)
sorts n numbers in place in O(n lgn)
3
Sorting algorithm
Quick sort : (chapter 7)
worst time complexity O(n2)
Average time complexity O(n lgn)
Decision tree model &
sorting in linear time: (chapter 8)
Lower bound (n lgn)
Counting sort
Radix sort
Order statistics
4
Pseudocode of selection sort
SELECTION-SORT(A) cost
1 for i 1 to length[A] 1 n
2 do min i n1
n 1
3 for j i+1 to length[A] (n i 1)
i 1 n 1
4 if A[j] < A[min] then (n i)
i 1
5 do min j n 1
(n i )
6 SWAP(A[i], A[min] ) n1 i 1
5
Analysis of selection sort
n 1 n 1
T (n) n (n 1) ( n i 1) 2 (n i ) (n 1)
i 1 i 1
(n 2)( n 1)
3n 2 n(n 1) (n 2 )
2
n 1 n 1
T (n) n (n 1) (n i 1) (n i ) (n 1) (n 2 )
i 1 i 1
T ( n ) ( n 2 )
The running time is insensitive to the input.
It needs (only) linear exchanges.
6
Pseudocode of bubble sort
BUBBLE-SORT(A) cost
1 for i length[A] downto 1 n1
n
2 for j 2 to i i
i 1 n 1
7
Analysis of bubble sort
The worst case: n n 1
T (n) ( n 1) i 2 i
i 1 i 1
n(n 1)
n 1 n( n 1) (n 2 )
2
T ( n ) ( n 2 )
(Almost) the complementary of selection sort.
The running time is about the same in the average case
and linear in the best case (not by this
implementation).
It needs much more exchanges than selection sort. 8