I am trying to figure out the median of a sorted array. So, what I know is that I need to find the middle element of the array and print it.
I feel like I can't just do arr[size / 2] because if it is odd, there will be a decimal and there will be no matching element in the array. So, I think I mainly need help finding the middle element without doing any mathematical operation on the size of the array.
// Unit 9 modularized.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<string>
#include <iomanip>
usingnamespace std;
// Declare functions.
int askStudents();
int* askMovies(int getStudents);
int* sortMovies(int* askMovies);
int getMedian(int getStudents, int* setMovies);
//Declare variables.
int getStudents;
int* setMovies;
int main()
{
getStudents = askStudents();
setMovies = askMovies(getStudents);
sortMovies(setMovies);
getMedian(getStudents, setMovies);
return 0;
}
int askStudents()
{
cout << "How many students were surveyed? ";
cin >> getStudents;
while (getStudents < 0)
{
cout << "Please enter a non-negative number: ";
cin >> getStudents;
}
return getStudents;
}
int* askMovies(int getStudents)
{
// Creating array "setMovies" with size of getStudents using pointer.
int *setMovies;
setMovies = newint[getStudents];
// Storing the amount of movies each student watched into setMovies array.
for (int i = 0; i < getStudents; i++)
{
cout << "How many movies did each student watch: ";
cin >> setMovies[i];
while (setMovies[i] < 0)
{
cout << "Please enter a non-negative number: ";
cin >> setMovies[i];
}
}
// Printint setMovies for test
for (int i = 0; i < getStudents; i++)
cout << setMovies[i];
cout << "\n";
return setMovies;
}
int* sortMovies(int* setMovies)
{
for (int i = 0; i < getStudents; i++)
{
for (int j = i + 1; j <getStudents; j++)
{
if (setMovies[i]>setMovies[j])
{
int temp = setMovies[i];
setMovies[i] = setMovies[j];
setMovies[j] = temp;
}
}
}
for (int i = 0; i < getStudents; i++)
cout << setMovies[i];
cout << "\n";
return setMovies;
}
int getMedian(int getStudents, int* setMovies)
{
float median;
if (getStudents % 2 == 0)
{
median = (setMovies[(getStudents / 2) - 1] + setMovies[(getStudents / 2)]) / 2;
cout << "The median is: " << median << endl;
}
else
{
median = setMovies[(getStudents / 2)];
cout << "The median is: " << median << endl;
}
return median;
}
If 'size' is an integer, arr[size / 2] is the middle element, because size / 2 does integer division. By the way, it's not possible to use a fractional number to index an array. arr[1.5] will give a compiler error.
You don't have to. size / 2 is an integer, always. For integer values of a and b, a / b = c is the integer farthest from zero such that abs(c * b) <= abs(a).