COE428-1
COE428-1
1
Algorithms & Data Structures
• Algorithm
• Steps to solve a problem
• Well-defined computational procedure that takes a
set of values as inputs and a set of values as outputs
2
Algorithms & Data Structures
3
The problem of sorting
Example:
Input: 8 2 4 9 3 6
Output: 2 3 4 6 8 9
4
Insertion sort
5
Insertion sort
j=2
A[2] = 2, key = 2
i=1
A[1] = 8, Key=2 8 > 2
Change A[i], A[i+1]
i=0
A[0+1]= 2, key = 2
1 2 3 4 5 6
8 8 4 9 3 6 7
2
Example of insertion sort
INSERTION-SORT (A, n) ⊳ A[1 . . n]
for j ← 2 to n
8 2 4 9 3 6 do key ← A[ j]
i←j–1
while i > 0 and A[i] > key
do A[i+1] ← A[i]
i←i–1
1 2 3 4 5 6 A[i+1] = key
j=3
A[3] = 4, key = 4
i=2
A[2] = 8, Key=4 8 > 4
Change A[i], A[i+1]
i=1
A[1+1]= 4, key = 4
1 2 3 4 5 6
2 8 8 9 3 6 8
4
Example of insertion sort
1 2 3 4 5 6 INSERTION-SORT (A, n) ⊳ A[1 . . n]
for j ← 2 to n
8 2 4 9 3 6 do key ← A[ j]
i←j–1
while i > 0 and A[i] > key
do A[i+1] ← A[i]
i←i–1
A[i+1] = key
9
Example of insertion sort
1 2 3 4 5 6 INSERTION-SORT (A, n) ⊳ A[1 . . n]
for j ← 2 to n
8 2 4 9 3 6 do key ← A[ j]
i←j–1
while i > 0 and A[i] > key
do A[i+1] ← A[i]
i←i–1
A[i+1] = key
10
Example of insertion sort
1 2 3 4 5 6 INSERTION-SORT (A, n) ⊳ A[1 . . n]
8 2 4 9 3 6 for j ← 2 to n
do key ← A[ j]
i←j–1
while i > 0 and A[i] > key
do A[i+1] ← A[i]
i←i–1
A[i+1] = key
11
Example of insertion sort
1 2 3 4 5 6
INSERTION-SORT (A, n) ⊳ A[1 . . n]
for j ← 2 to n
8 2 4 9 3 6 do key ← A[ j]
i←j–1
while i > 0 and A[i] > key
do A[i+1] ← A[i]
i←i–1
A[i+1] = key
12
Example
1 2
of insertion
3 4
sort
5 6
INSERTION-SORT (A, n) ⊳ A[1 . . n]
8 2 4 9 3 6 for j ← 2 to n
do key ← A[ j]
i←j–1
while i > 0 and A[i] > key
do A[i+1] ← A[i]
i←i–1
A[i+1] = key
13