For an assignment the following test input is as follows:
#include <cmath>
const double EPS = 0.00001;
int array[] = {1,5,7,4,2,6,3,9,8};
double result = findMedian(array, 9);
ASSERT_TRUE(fabs(result-5.0) < EPS);
************************Here is my file to find the median from the array
#include <iostream>
#include <algorithm>
using namespace std;
//function used to sort the array
void sort(int* arrayPtr, int size)
{
int i, j;
//nested loop used to sort out the array
for (i=0;i<size;i++)
for (j=i+1;j<size;j++)
if (*(arrayPtr + j)<*(arrayPtr + i))
{
int temp = *(arrayPtr + j);
*(arrayPtr+j) = *(arrayPtr + i);
*(arrayPtr+i) = temp;
}
}
//Function used to print out the sorted array
void printMedian(int array[], int size)
{
for (int i=0;i<size;i++)
cout << array[i] << ' ';
}
//Function that finds the median
int findMedian(int array[], int size)
{
int median, mid;
mid = size/2;
if (size%2 == 0)
{
//Median calculation whether array is even or odd
median=(array[mid] + array[mid-1])/2;
}
else
{
median = (array[mid]);
}
return median;
}
************** When I create my own main file I get the correct output.. any thoughts why the input above doesn't work with my code? Thanks.
#include "findMedian.cpp"
int main()
{
int array[] = {20, 2, 8, 0, 0, 50, 1, 2, 40, 20, 100, };
int* arrayPtr = array;
int size = 11;
int median;
sort(arrayPtr, size);
printMedian(array,size);
median = findMedian(array, size);
cout << endl << "Median is: " << median << endl;
system("pause");
return 0;
}
Last edited on