Skip to content

Instantly share code, notes, and snippets.

@snoopspy
Last active August 29, 2015 14:17
Show Gist options
  • Save snoopspy/bdc331b5c56d251991d7 to your computer and use it in GitHub Desktop.
Save snoopspy/bdc331b5c56d251991d7 to your computer and use it in GitHub Desktop.
How to get third largest number in array
#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;
}
@snoopspy
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment