Algorithms: Finding The Smallest Element in An Array Find The Smallest and Make It The First
Algorithms: Finding The Smallest Element in An Array Find The Smallest and Make It The First
Algorithms
Algorithms are ways of solving problems. There is
a technical definition that basically says an
algorithm is a clear set of instructions which if
followed will lead to a correct problem solution in
a finite amount of time
Sorting is a very important problem and has been
studied extensively. We begin by looking at a
simple sorting algorithm
We build up to the algorithm by starting with
finding the smallest element in an array
Introduction to Algorithms
varA = 1
varB = 4
varA = varB
varB = varA
7/17/2011
Doing it right:
varA = 1
varB = 4
temp = varB
varB = varA
varA = temp
10
11
10
11
10
10
11
10
11
10
11
11
10
12
7/17/2011
Algorithm Structure
11
10
10
11
Loop Setup
14
In general
15
16
18
7/17/2011
Tricky Bits
Note the -1 and +1 in the loop limits. Getting
those right takes some thought
Does the code work on arrays with just one
element? With two elements? With no
elements? (Nothing to sort, but we want to
avoid a runtime error.) What if the data is
already sorted?
19
20
Bubble sort
Quicksort
Heapsort
Mergesort
Bucket sort
21
Comparison of n, n log n, n2
1800
1600
1400
1200
1000
n^2
n log n
800
22
600
400
200
0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
23
24
7/17/2011
Importance of Algorithms
Software Engineering
26