Chapter9 Part1
Chapter9 Part1
Chapter 9 (Sorting):
Elementary Algorithms
Sorting is important
Why do we sort data?
Because it makes searching so much easier!
Suppose we’re looking for a student number…
7 3 5
What makes a good sorting algorithm?
The number of actions will depend on the order of elements
Consider:
Every element
needs to move 7 3 5 Worst case
No elements need
to move 3 5 7 Best case
5 1 3 4
2 2 2 2 1 1 1 1 1
5 5 5 2 2 2 2 2 2
1 1 5 5 5 5 3 3 3
3 3 3 3 3 5 5 5 4
4 4 4 4 4 4 4 5 5
Insertion Sort:
Efficiency
n = data.length
0 1, 2, … (n – 2), (n – 1) ½ of the
worst case?
Insertion Sort: Efficiency
insertionSort(data[ ])
for i = 1 to n-1
tmp = data[i];
j = i – 1;
while j >= 0 && data[j] > tmp
data[j + 1] = data[j]; j--;
data[j + 1] = tmp;
2 2 1 1 1 1 1
5 5 5 2 2 2 2
1 1 2 5 3 3 3
3 3
3 3 5 4 4
4 4 4
4 4 5 5
Selection Sort: Efficiency
How many times will
selectionSort(data[ ]) the outer loop (n – 1)
for i = 0 to n-1 execute?
select the smallest element among How many times
data[i], …, data[n-1]; will the inner loop
swap it with data[i]; execute?
3
best case avg case worst case
4 (largest first, the rest
(ordered) (random) is ordered)
2 2 2 1 1 1 1 1
5 5 1 2 2 2 2 2
5
1 1 5 3 3 3 3
3 3
3 3 5 4 4 4
4 4 4
4 4 5 5 5
(n – 1)
Bubble Sort How many times will
bubbleSort(data[ ]) the outer loop
for i = 0 to n-2 execute?
for j = n-1 down to i+1 How many times
if elements in positions j and j-1 will the inner loop
are out of order, swap them; execute?
(n – 1) , (n – 2), … 2, 1
33 98 74 13 55 20 77 45 64 83
33 98 74 13 55 20 77 45 64 83
33 64 74 13 55 20 77 45 98 83
33 64 74 13 55 20 77 45 98 83
gap/1.3 = 5
33 64 74 13 55 20 77 45 98 83
20 64 74 13 55 33 77 45 98 83
20 64 74 13 55 33 77 45 98 83
20 64 74 13 55 33 77 45 98 83
20 64 45 13 55 33 77 74 98 83
20 64 45 13 55 33 77 74 98 83
20 64 45 13 55 33 77 74 98 83
Comb Sort
20 64 45 13 55 33 77 74 98 83
13 64 45 20 55 33 77 74 98 83 gap/1.3 = 3
13 64 45 20 55 33 77 74 98 83
13 55 45 20 64 33 77 74 98 83
13 55 45 20 64 33 77 74 98 83
13 55 33 20 64 45 77 74 98 83
13 55 33 20 64 45 77 74 98 83
13 55 33 20 64 45 77 74 98 83
13 55 33 20 64 45 77 74 98 83
13 55 33 20 64 45 77 74 98 83
13 55 33 20 64 45 77 74 98 83
13 55 33 20 64 45 77 74 98 83
13 20 33 55 64 45 77 74 98 83
gap/1.3 = 2 13 20 33 55 64 45 77 74 98 83
13 20 33 55 64 45 77 74 98 83
13 20 33 45 64 55 77 74 98 83
13 20 33 45 64 55 77 74 98 83
13 20 33 45 64 55 77 74 98 83
13 20 33 45 64 55 77 74 98 83
13 20 33 45 64 55 77 74 98 83
Comb Sort
gap/1.3 = 1 Efficiency?