//Devin Scheu CS1A Chapter 9, P. 538, #9
//
/**************************************************************
*
* DETERMINE MEDIAN OF SORTED INTEGER ARRAY
* ____________________________________________________________
* This program determines the median of a set of integer values
* in a sorted array.
* ____________________________________________________________
* INPUT
* arraySize : The number of elements in the array
* values : The array of integers
*
* OUTPUT
* medianValue : The median of the array
*
**************************************************************/
#include <iostream>
#include <iomanip>
using namespace std;
// Function to swap two integers using pointers
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Function to perform bubble sort using pointers
void bubbleSort(int* arr, int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (*(arr + j) > *(arr + j + 1)) {
swap(arr + j, arr + j + 1);
}
}
}
}
// Function to find median using pointer notation
double findMedian(int* arr, int size) {
if (size % 2 == 1) {
return static_cast<double>(*(arr + size / 2));
} else {
double mid1 = static_cast<double>(*(arr + size / 2 - 1));
double mid2 = static_cast<double>(*(arr + size / 2));
return (mid1 + mid2) / 2.0;
}
}
int main () {
//Variable Declarations
int arraySize; //INPUT - The number of elements in the array
int* values; //INPUT - The array of integers
double medianValue; //OUTPUT - The median of the array
//Prompt for Input
cout << "Enter the number of elements: ";
cin >> arraySize;
cout << arraySize << endl;
while (arraySize <= 0) {
cout << "\nError: Please enter a positive number: ";
cin >> arraySize;
cout << arraySize << endl;
}
//Allocate dynamic array
values = new int[arraySize];
//Input Values
for (int i = 0; i < arraySize; i++) {
cout << "Enter value " << (i + 1) << ": ";
cin >> *(values + i);
cout << *(values + i) << endl;
}
//Sort the array
bubbleSort(values, arraySize);
//Calculate Median
medianValue = findMedian(values, arraySize);
//Separator and Output Section
cout << "-------------------------------------------------------" << endl;
cout << "OUTPUT:" << endl;
//Output Result
cout << fixed << setprecision(2);
cout << left << setw(25) << "Median:" << right << setw(15) << medianValue << endl;
//Clean up memory
delete[] values;
} //end of main()