We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Algorithms
- Sorting
- Find the Median
- Discussions
Find the Median
Find the Median
Sort by
recency
|
553 Discussions
|
Please Login in order to post a comment
include
include
using namespace std;
int findMedian(int arr[], int n) { sort(arr, arr + n); return arr[n / 2]; }
int main() { int n; cin >> n; int arr[n]; for (int i = 0; i < n; i++) { cin >> arr[i]; }
}
Sort, then pick the midpoint seemed the easiest. But sort is O(n log n), right? If so, can we use a better sort and get to O(n)? So,if we look at a sorted array and median is midpoint, then we can assume the NthSmallest integer where n is the midpoint is what we are looking for. Then we only have to adjust our sort until then.
Typescript:
JavaScript:
Java: