Method1) Traditional
#include
using namespace std;
int main()
{
//Input the total number of elements
int n;
cout<<”\nEnter the number of elements=”;
cin>>n;
//Declare an array and also input the
//array elements
int a[n];
cout<<”\nEnter the elements=”;
for(int i=0;i
int minNo, maxNo;
//If there is less than two elemnst then
//no point in taking it forward
if(n<2)
{
cout<<”Too less elements”;
exit(0);
}
//find the max and min number from first
//two elements in the array
if(a[0]>a[1])
{
minNo=a[1];
maxNo=a[0];
}
else
{
minNo=a[1];
maxNo=a[0];
}
//Check from third element to end
//Pick two numbers at a time and
//compare themeselves. Then compare the
//lesser element with min element and
//greater element with max element
for(int i=2;(i+1)
if(a[i]
{
if(a[i]
if(a[i+1]>maxNo)
maxNo=a[i+1];
}
else
{
if(a[i+1]
if(a[i]>maxNo)
maxNo=a[i];
}
}
cout<<”\nMax number is=”<
return 0;
}
Method2) O(3/2n) Comparison
Can be done in O(3/2n) comparison
Compare first two number and store min and max
From next time read two element from the array and compare them self
Now compare the min number with the old min and max number with the old max
So total 3 comparisons instead of 4
#include
using namespace std;
int main()
{
//Input the total number of elements
int n;
cout<<”\nEnter the number of elements=”;
cin>>n;
//Declare an array and also input the
//array elements
int a[n];
cout<<”\nEnter the elements=”;
for(int i=0;i
int minNo, maxNo;
//If there is less than two elemnst then
//no point in taking it forward
if(n<2)
{
cout<<”Too less elements”;
exit(0);
}
//find the max and min number from first
//two elements in the array
if(a[0]>a[1])
{
minNo=a[1];
maxNo=a[0];
}
else
{
minNo=a[1];
maxNo=a[0];
}
//Check from third element to end
for(int i=2;i
//If there is a number which is lesser
//than the min that has been found so far
//then update the min number
if(a[i]
//If there is a number which is greater
//than the max that has been found so far
//then update the max number
if(a[i]>maxNo)
maxNo=a[i];
}
cout<<”\nMax number is=”<
return 0;
}

Leave a Reply
You must be logged in to post a comment.