# Find the Second Largest Number in an Unsorted Array

Write a Program to find the second largest number in an unsorted array. Given an array of unsorted values find the second largest number in an array.

For example – Let’s take an array.

arr[] = { 4, 1, 5, 2, 8, 0, 3, 55}

The second largest element in this array is 8.  So how do you find the second largest number in an array ?  There are multiple ways by which you can solve this problem.

Find Second Largest Number in an Array

First Approach : Sort an Array

The simple approach is  to sort an array using sorting algorithm. After sorting an array element at n-2 index will be the second largest element.

You can use following sorting algorithms.

iii) Bubble Sort

Subscribe Our Tutorials

iv) Merge Sort

Selection sort, insertion sort and bubble sort are not suitable for large data sets as their time complexity is O(n2) . You can use Merge Sort or Quick Sort for large data sets.

NOTE –  If  values of an array is  repeated then this approach won’t work. Then the best approach is to traverse an array to find the second largest element.

Second Approach : Traverse an array

The best approach is to traverse an array to find the second largest number in an array. Using this approach maintain two flags one for highest and other for the second highest number. The time complexity of this approach is O(n).

## PHP Code to Find the Second Largest Number in an unsorted Array

PHP provides several functions for sorting an array. After sorting an array, You can easily print the second highest element.

But let’s do without using any in-built functions.

### Conclusion

There are multiple ways by which you can solve this problem efficiently. I have explained two approaches. If you want to share any other approach to solve this problem efficiently then let us know through your comment.

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , , . Bookmark the permalink.
• Ajitav Mohanty

Please find an optimised solution for the above problem:

“http://quickinfobox.blogspot.in/2016/03/an-optimised-approach-to-find-second.html”

/* This is much simpler logic compared to the above one */
#include

int main()

{

int a[]={70,4,8,10,14,9,7,6,5,3,2,69};

int f=a[0];

int s=a[1];

int temp;

if(s>f){

temp=f;

f=s;

s=temp;

}

int i;

for(i=2;is){

if(a[i]>f){

s=f;

f=a[i];

}

else

s=a[i];

}

}

printf(“second= %d”, s);

printf(“nmax= %d”, f);

}