Last active
April 8, 2019 22:33
-
-
Save kurtkaiser/141c8f1d3f081f277513c08973b01f55 to your computer and use it in GitHub Desktop.
Efficiently calculates and returns the median, as a double, of an array of integers
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
// Efficiently Calculates Median | |
// Kurt Kaiser | |
#include <iostream> | |
#include <algorithm> | |
using std::cout; | |
using std::endl; | |
// Defining a function to find the median of an array of ints, | |
// return type is double because median of ints can be decimals | |
double findMedian(int intArray[], int length) { | |
double median; | |
// Sorting algorithm used for effiecieny | |
std::sort(intArray, intArray + length); | |
// Calculate the median for odd length intArrays | |
median = intArray[(length / 2)]; | |
// Check if array has an even length | |
if (length % 2 == 0) { | |
// if even intArray, get next number in intArray and divide by 2 | |
median = (median + intArray[length / 2 - 1]) / 2; | |
} | |
// Return the calculated median | |
return median; | |
} | |
int main() { | |
int arrayOne[7] = { 1, 2, 3, 4, 5, 99, 88 }; | |
cout << findMedian(arrayOne, 7) << endl; | |
int arrayTwo[4] = { 1, 2, 3, 4}; | |
cout << findMedian(arrayTwo, 4) << endl; | |
int arrayThree[9] = { 51, 10, 15, 20, 87, 11, 588, 3, 9 }; | |
cout << findMedian(arrayThree, 9) << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment