Last active
August 29, 2015 14:17
-
-
Save snoopspy/bdc331b5c56d251991d7 to your computer and use it in GitHub Desktop.
How to get third largest number in array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <assert.h> // for assert | |
#include <iostream> // for std::cout | |
#include <climits> // for INT_MAX | |
int get_third_largest_number(int* arr, int n) | |
{ | |
int max1 = -INT_MAX; | |
int max2; | |
int max3; | |
assert(n >= 3); | |
for(int i = 0; i < n; i++) | |
{ | |
if(arr[i] > max1) | |
{ | |
max3 = max2; | |
max2 = max1; | |
max1 = arr[i]; | |
} else | |
if(arr[i] > max2) | |
{ | |
max3 = max2; | |
max2 = arr[i]; | |
} else | |
if(arr[i] > max3) | |
max3 = arr[i]; | |
} | |
return max3; | |
} | |
int main() | |
{ | |
int a[] = {1, 2, 3, 4, 5, 6, 7,8 , 9, 10}; | |
int third = get_third_largest_number(a, 10); | |
std::cout << third << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
get_third_largest_number function needs to check if array size(n) is equal or greater than 3, so add assert function at the end of the function body.