Chapter 2 – The Fundamentals

advertisement
Chapter 2 – The Fundamentals
input
output
definiteness
correctness
finiteness
generality
Pseudocode
Finding the largest element in a list
Algorithm 1: Finding the maximum Element in a Finite Sequence
{page 122 in Rosen}
procedure max(a1, a2, …, an: distinct integers)
max  a1
// initialize max to the first element of the list
for i  2 to n
if max < ai then max  ai
return(max) // max is the largest element
p. 130 # 17 Describe an algorithm that locates the first
occurrence of the largest element in a finite list of integers where
the integers are not necessarily distinct.
procedure max(a1, a2, …, an: integers)
max  a1
{initialize max to the first element of the list}
Search algorithms
Algorithm 2 The Linear Search Algorithm
Procedure linear search(x : int, a1, a2, ...,an: distinct int)
{ return the location of x in the list, or 0 if x is not on list}
i1
while (i  n and x  ai)
ii+1
if i  n then location  i
else location  0
Is there a more efficient searching algorithm?
Algorithm 3 The Binary Search Algorithm
Procedure binary search( x: int, a1, a2, ...,an: increasing int)
i  1 {left endpoint of search interval}
j  n {right endpoint of search interval}
while i < j
m  (i+j)/2
if x > am then i  m + 1
else j  m
if x = ai then location  i
else location  0
Sorting algorithms
Bubble Sort
Basic idea:
1.
2.
3.
Structuring the Loops
Algorithm 4 The Bubble Sort
procedure bubblesort(a1, a2, … , an)
for i  1 to n -1
{ a1, a2, … , an is now in increasing order}
Download