Hapter: Simple Sorting and Searching Algorithms
Hapter: Simple Sorting and Searching Algorithms
By: Tigabu Y.
CHAPTER OVERVIEW
Simple Sorting algorithms
o Selection sort
i.e.
2 4 5 7 8 How many comparisons?
(n-1)+(n-2)+…+1 = O(n2)
How many swaps?
n = O(n)
6
7 2 8 5 4 2 7 5 4 8 2 5 4 7 8 2 4 5 7 8
2 7 8 5 4 2 7 5 4 8 2 5 4 7 8 2 4 5 7 8
2 7 8 5 4 2 5 7 4 8 2 4 5 7 8
2 7 5 8 4 2 5 4 7 8
2 7 5 4 8
Sort: 34 8 64 51 32 21
34 8 64 51 32 21
The algorithm sees that 8 is smaller than 34 so it swaps.
8 34 64 51 32 21
51 is smaller than 64, so they swap.
8 34 51 64 32 21
The algorithm sees 32 as another smaller number and
moves it to its appropriate location between 8 and 34.
8 32 34 51 64 21
The algorithm sees 21 as another smaller number and
moves into between 8 and 32.
Final sorted numbers:
8 21 32 34 51 64 14
17
18
19
20
if(found==0)
index=-1;
return index;
}
21
22
23
return index;
} 24
nlogn
25
ANY Q?
26