ANSWERS TO REVIEW QUESTIONS 181
ALGORITHMS
2.1 Write pseudo code for an algorithm for finding the square root of a number.
guess <-- number / (1 + count of digits in the
number)
while(absoluteValue((guess * guess) - number) > .01
){
guess = (guess + number/guess) / 2
}
return guess
(from: http://www.homeschoolmath.net/teaching/square-root-algorithm.php)
2.2 Write pseudo code for finding the mean of a set of numbers.
mean( list_of_numbers )
length <-- length of list_of_numbers
index <-- 1
sum <-- 0
while index <= length {
sum <-- sum + list_of_numbers[index]
index <-- index + 1
}
return sum / length
2.3 Count the primitive operations in your algorithm to find the mean. What is the order of growth of your
mean algorithm?
setup 4
loop 5 * length (length = n, the count of numbers to be averaged)
return 2
??( n )
2.4 Write pseudo code for finding the median of a set of numbers.
median( list_of_numbers )
length <-- length of list_of_numbers
merge_sort( list_of_numbers )
if length is odd
// return middle number
return list_of_numbers[(length + 1) / 2]
else
// find subscripts of 2 middle values
m1 <-- length / 2
m2 <-- m1 + 1
// and return the average of the middle two
return (list_of_numbers[m1]+list_of_numbers[m2]) /
2
end
2.
Pages:
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499