Advertisement
Mr_kindle

²ndlargestwithoutsorting.c

Nov 3rd, 2022 (edited)
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.23 KB | None | 0 0
  1.  
  2.  
  3.  
  4. /*This code found the 2nd largest element without sorting the array*/
  5. /*This code works only when all elements are distinct*/
  6. #include<stdio.h>
  7. #include<malloc.h>
  8.  
  9. int main()
  10. {
  11.    int *arr,i,j,max,n,max2;
  12.      printf("Enter number of elements(all elements should be distinct):. ");
  13.     scanf("%d",&n);
  14.     arr= calloc(n,sizeof(int));
  15.     /*Enter all (distinct) elements of array*/
  16.     for(i=0;i<n;i++)
  17.     {    printf("Enter element %d: ",i+1);
  18.         scanf("%d",&arr[i]);
  19.     }
  20.     max=arr[0];//let first element is maximum
  21. /*First of all found the Largest*/
  22.     for(i=0;i<n;i++)
  23.     {    for(j=i+1;j<n;j++)
  24.             {    if(arr[j]>arr[i] && arr[j]>max)
  25.                 max=arr[j];
  26.             }
  27.     }
  28.    //printf("\n%d",max);
  29. /*Now to find 2nd Largest*/
  30. max2=arr[0];
  31.     for(i=0;i<n;i++)
  32.     {    for(j=i+1;j<n;j++)
  33.             {  if(arr[j]==max)
  34.                     continue;
  35.              if(arr[j]>arr[i])
  36.                 max2= arr[j];
  37.             }
  38.     }
  39.     printf("\nSecond Largest Number = %d",max2);
  40.     /*Printing array to show that array is not sorted*/
  41.    
  42.     printf("\n Here is the list:\n");
  43.     for(i=0;i<n;i++)
  44.     {    printf("%d ",arr[i]);
  45.    
  46.     }
  47.     free(arr);
  48.    
  49.     return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement