Find Max. and Next Max.
Algorithm
Input An array of numbers Output Max and next max Complexity O(n) 1 Maximum(Array A) 2 Set n=number of element in array; 3 Compare first two numbers 4 If Array[first] is greater then set first= max and second=nextmax 5 otherwise set first=nextmax and second=max; 6 for i=2 to n do 7 if Array[i] > max 8 store max in temp; 9 assign Array[i] to max; 10 if temp > nextmax 11 assign temp to nextmax; 12 else 13 if array[i] > nextmax 14 assign array[i] to nextmax; 15 Print max and nextmax;
Algorithm Description
Algorithms stores value of the largest of first two numbers in the max variable and other one in nextmax variable. It keeps on comparing every value of the array with these variables and updating the values of these variables based on the comparison.
C Code
/** Code Written By: Ankit Babbar
Date: 26 March,2011
Quesn: Running on safe path
**/
#include<stdio.h>
#include<conio.h>
int main()
{
int a[50],num,max,nmax,t,i;
clrscr();
printf("how many numbers you want to enter ");
scanf("%d",&num);
printf("enter the no.");
for(i=0;i<num;i++)
scanf("%d",&a[i]);
if(a[0]>a[1])
{
max=a[0];
nmax=a[1];
}
else
{
max=a[1];
nmax=a[0];
}
for(i=2;i<num;i++)
{
if(a[i]>max)
{
t=max;
max=a[i];
if(t>nmax)
nmax=t;
}
else if(a[i]>nmax)
nmax=a[i];
}
printf("Max no is %d and next max no is %d : ",max,nmax);
return 0;
}