Wednesday 27 July 2016

C program to find 2nd minimum and 2nd maximum

Hello friends !
This program sounds quite simple but its little confusing rather , the algorithms i had used before were appropriate for some cases only . I guess this program contains no error or if any just let me know .


#include<stdio.h>
#define largest_value 1000
int main()
{
int i,j,k,n;
int max,min,max2,min2,temp1,temp2;
printf("Enter size of array :\n");
scanf("%d",&n);
int array[n];
printf("Enter the elements of array:\n");

for(i=0;i<n;i++)
{
scanf("%d",&array[i]);
}

max=max2 = array[0];
min=min2= largest_value;
for(i=0;i<n;i++)
{
    if(array[i]<min)
    {
    min=array[i];
    }

    if(array[i]>max)
    {
    temp2=max;
    max=array[i];
    max2=temp2;
    }
}
for(i=0;i<n;i++)
{ if(array[i]<min2 && array[i]!=min)
    min2=array[i]; }

printf("max %d 2nd max %d min %d 2nd min %d \n",max,max2,min,min2);
}

 /*
accessing array by address
Q3 Find second largest and second smallest element from array.
*/

#include<stdio.h>
#define largest_value 1000
int minmax2();
int main()
{
int i,j,k,n;
int max,min,max2,min2,temp1,temp2;
printf("Enter size of array :\n");
scanf("%d",&n);
int array[n];
printf("Enter the elements of array:\n");

for(i=0;i<n;i++)
{
scanf("%d",&array[i]);
}
minmax2(array,n,&min,&min2,&max,&max2);
}

//function

int minmax2(int *array,int n,int *min,int *min2,int *max,int *max2)
{
    int i,temp1,temp2;
    *max=*max2 = *array;
    *min=*min2= largest_value;
    for(i=0;i<n;i++)
    {
    if(*(array+i)<*min)
    {
    *min=*(array+i);
    }

    if(*(array+i)>*max)
    {
    temp2=*max;
    *max=*(array+i);
    *max2=temp2;
    }
    }
    for(i=0;i<n;i++)
    { if(*(array+i)<*min2 && *(array+i)!=*min)
    *min2=*(array+i); }

    printf("2nd max %d \n2nd min %d \n",*max2,*min2);
}




Thanking you !

2 comments :

  1. Will it not be easier if we sort the array then find req parameters??

    ReplyDelete
    Replies
    1. I don't think so. Bcz sorting requires more steps than this.
      Also if we sort , what if there are two or more numbers with minimum or maximum value ? So , for that comparison also we need to run a loop again ,which will again increase time complexity . So, i think sorting will not work better here !

      Delete