Skip to content

Commit cab7946

Browse files
committed
Adds find the median solution
1 parent 627ac56 commit cab7946

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

problem-solving/find-the-median.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// https://www.hackerrank.com/challenges/find-the-median/problem
2+
int findMedian(vector<int> arr) {
3+
sort(arr.begin(), arr.end());
4+
5+
int len = arr.size();
6+
// If number of element in the list is odd
7+
// Return middle element
8+
if(len % 2 != 0)
9+
return arr[(len/2)];
10+
11+
// Return average of the two middle elements
12+
int a = arr[len/2];
13+
int b = arr[(len/2)+1];
14+
15+
return (a + b)/2;
16+
17+
}

0 commit comments

Comments
 (0)