COP 3530, Discrete Data Structures and Algorithms, Summer 1999, Homework 2

884 Words2 Pages

Class Notes: Data Structures and Algorithms

Summer-C Semester 1999 - M WRF 2nd Period CSE/E119, Section 7344

Homework #2 -- Due Fri 28 May 1999 : 09.30am

* Question 1. Assume that an n-element array (vector) a contains distinct integers arranged in no particular order. Write an algorithm to find the value and location of (a) the mean of a and (b) the value v in a closest to the mean. Note: If v equals the mean, then v is the value closest to the mean.

Example. If a = (1,2,3,5,4,6,7,9), then the mean equals 37/8 = 4.625. The value 5, which is in the fourth location (i = 4), happens to be the value closest to the mean.

Answer:

FindMean(a : array [1..n] of int):

{ sum = 0; posmean = -1, posclose = -1

for i = 1 to n do:

sum = sum + a[i]

endfor

mean = float(sum) / n

mdif = 9E13

for i = 1 to n do:

dif = abs(a[i] - mean)

if (dif < mdif) then

if (dif = 0) then

More about COP 3530, Discrete Data Structures and Algorithms, Summer 1999, Homework 2

Open Document