Write a program that finds the second largest element in a given list of N numbers.
507Program:
/* This program finds the second largest in a given list of numbers */ #include int Num, firstLarge, secLarge; int N, i; void main() { printf ("\n Enter the size of the list"); scanf ("%d", & N); printf ("\n Enter the list one by one"); scanf ("%d", &Num); firstLarge = Num; secLarge = - 9999; for (i = 2; i <= N; i++) { scanf ("%d", &Num); if (firstLarge < Num) {secLarge = firstLarge; firstLarge = Num; } else if (secLarge < Num) secLarge = Num; } printf ("\n Second Large = %d", secLarge); }
Output:
Enter the size of the list: 5 Enter the list one by one 1 2 3 4 5
Explanation:
The above discussed search through a list, stored in an array, has the following characteristics:
- The search is linear.
- The search starts from the first element and continues in a sequential fashion from element to element till the desired entry is found.
- In the worst case, a total number of N steps need to be taken for a list of size N.
Thus, the linear search is slow and to some extent inefficient. In special circumstances, faster searches can be applied.
For instance, binary search is a faster method as compared to linear search. It mimics the process of searching a name in a directory wherein one opens a page in the middle of the directory and examines the page for the required name. If it is found, the search stops; otherwise, the search is applied either to first half of the directory or to the second half.
This Particular section is dedicated to Programs only. If you want learn more about Data Structure. Then you can visit below links to get more depth on this subject.