Write a Program to Find Out The Minimum and Maximum Number is an Array


Find The Minimum & Maximum No in an Array

Introduction
We start by looking more closely at the statistics known as the minimum. This number is the data value that is less than or equal to all other values in our set of data. If we were to order all of our data in ascending order, then the minimum would be the first number in our list. Although the minimum value could be repeated in our dataset, by definition this is a unique number.
Now we turn to the maximum. This number is the data value that is greater than than or equal to all other values in our set of data. If we were to order all of our data in ascending order, then the minimum would be the last number listed. The maximum is a unique number for a given set of data. This number can be repeated, but there is only one maximum for a data set.


Algorithm:
Step 1: START
Step 2: READ THE NUMBER N
Step 3: [INITIALIZE] I=0
Step 4: REPEAT STEP 4 TO 6 WHILE I<N
Step 5: READ THE ARRAY ARR[I]
Step 6: SET I=I+1
Step 7: SET MAX=ARR[0] 
Step 8: SET MIN=ARR[0]
Step 9: [INITIALIZE] I=1
Step10: REPEAT STEP 10 TO 15 WHILE I<N
Step 11: IF ARR[I]>=MAX THEN GO TO Step 12
Step 12: SET MAX=ARR[I]
Step 13: IF ARR[I]<=MIN THEN GO TO Step 14
Step 14: SET MIN=ARR[I]
Step 15: SET I=I+1
Step 16: PRINT MIN & MAX
Step 17: STOP


Program to Find out the Minimum and Maximum number is an array:
#include<stdio.h>
#include<conio.h>
main()
{
int arr[100],i,n,min,max;
printf("\n Enter the no of elements: ");
scanf("%d",&n);
printf("\n Enter the value of elements: ");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
min=arr[0];
max=arr[0];
for(i=1;i<n;i++)
{
if(arr[i]>=max)
{
max=arr[i]; 
}
if(arr[i]<=min)
{
min=arr[i];
}}
printf("\n The minimum element is %d", min);
printf("\n The maximum element is %d", max);
getch();
}


Output:

Here is the output generated by the program-
1st case:



2nd case:

 


Discussion:
If efficiency is not a concern computing the minimum and maximum in an array is successively done. Since they both are O(n) and need n-1 comparisons it’s natural to think that combining the two tasks will be O(n) and 2n – 2 comparisons. However, we can reduce the number of comparisons!

Instead of taking only one item from the array and comparing it against the minimum and maximum we can take a pair of items at each step. Thus we can first compare them and then compare the smaller value with the currently smallest value and the greater item with the currently greatest value. This will make only 3 comparisons instead of 4.

Post a Comment

0 Comments