Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*This code found the 2nd largest element without sorting the array*/
- /*This code works only when all elements are distinct*/
- #include<stdio.h>
- #include<malloc.h>
- int main()
- {
- int *arr,i,j,max,n,max2;
- printf("Enter number of elements(all elements should be distinct):. ");
- scanf("%d",&n);
- arr= calloc(n,sizeof(int));
- /*Enter all (distinct) elements of array*/
- for(i=0;i<n;i++)
- { printf("Enter element %d: ",i+1);
- scanf("%d",&arr[i]);
- }
- max=arr[0];//let first element is maximum
- /*First of all found the Largest*/
- for(i=0;i<n;i++)
- { for(j=i+1;j<n;j++)
- { if(arr[j]>arr[i] && arr[j]>max)
- max=arr[j];
- }
- }
- //printf("\n%d",max);
- /*Now to find 2nd Largest*/
- max2=arr[0];
- for(i=0;i<n;i++)
- { for(j=i+1;j<n;j++)
- { if(arr[j]==max)
- continue;
- if(arr[j]>arr[i])
- max2= arr[j];
- }
- }
- printf("\nSecond Largest Number = %d",max2);
- /*Printing array to show that array is not sorted*/
- printf("\n Here is the list:\n");
- for(i=0;i<n;i++)
- { printf("%d ",arr[i]);
- }
- free(arr);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement