CS 202
Epp section ???
Aaron Bloomfield
1
What is an algorithm?
An algorithm is a finite set of precise
instructions for performing a computation or for
solving a problem
Sorting a list
the
maximum
9
7
4
a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
4
10
9
8
7
6
5
4
3
2
6
Properties of algorithms
Algorithms generally share a set of properties:
Searching algorithms
Given a list, find a specific element in the
list
We will see two types
Linear search
a.k.a. sequential search
Binary search
a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
4
1
8
7
6
5
4
3
2
11
a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
4
1
10
9
8
7
6
5
4
3
2
11
12
13
while i < j
begin
m := (i+j)/2
if x > am then i := m+1
else j := m
end
if x = ai then location := i
else location := 0
location
14
a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
2
1
6
7
10 12 14 16 18 20
5
8
7
6
10
8
7
15
while i < j
begin
m := (i+j)/2
if x > am then i := m+1
else j := m
end
if x = ai then location := Ii
else location := 0
location
15
a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
2
1
6
8
10 12 14 16 18 20
5
8
7
10
8
16
17
It takes 3 steps
It takes 4 steps
It takes 6 steps
Sorting algorithms
Given a list, put it into some order
Bubble sort
Insertion sort
19
22
Worst case is when the while keeps i at 1, and the for loop runs lots of
times
If i is 1, the inner for loop runs 1 time (k goes from 0 to 0) on the first
iteration, 1 time on the second, up to n-2 times on the last iteration
Linear: n steps
Binary: log2 n steps
Binary search is about as fast as you can get
Sorts
Bubble: n2 steps
Insertion: n2 steps
There are other, more efficient, sorting techniques
In principle, the fastest are heap sort, quick sort, and merge
sort
These each take take n * log2 n steps
In practice, quick sort is the fastest, followed by merge sort
27