3.8 Sample algorithms 81
Maximum and minimum of an array
The algorithm implemented in the following code identifies the maximum
number in an array,a[i], wherei=1, 2 ,...N. We begin by assuming that
the maximum is the first entry,a[1], and update the maximum by successive
comparisons:
int maxpos=1;
for(int i=2; i<=N; i++)
{
if( a[i] > a[maxpos] )
{
maxpos=i;
}
}
A slight variation yields the minimum:
int minpos=1;
for(int i=2; i<=N; i++)
{
if( a[i] < a[minpos] )
{
minpos=i;
}
}
Ranking an element of an array
Next, we consider an algorithm that ranks a specified element in a nu-
merical arraya[l], wherel=1, 2 ,...N. If the specified element is the largest
number in the array, its rank is 1; if the specified element is the smallest number
in the array, its rank isN.
The ranking algorithm is based on the observation that, ifa[i]isthe
element to be ranked, then its rank is equal to one plus the number of times
thata[i]<a[j]forj=1, 2 ,...,Nandj=i. The last exception is included to
safeguard against round-off error. The implementation of the algorithm is:
rank = 1;
for(int j=1; j<=N; j++)
{
if(a[i]<a[j] && i!=j) rank++;
}