1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
|
#include <iostream>
#include <conio.h>
#include <cstdlib>
#include <ctime>
using namespace std;
int main
{
int* randomArray(int, int); /*This function creates an array of random numbers
of a given size within a given range*/
void displayArray(int*, int); //This function displays the array of random numbers
void sortData(int*, int); //Sorts the array data into ascending order
double findMed(int*, int); //Determines the median of the array
int main()
{
srand(time(NULL));
int size = 0;
int range = 100;
cout << "Enter the size of the array: ";
cin >> size;
cout << endl;
int* iptr = randomArray(size, range);
cout << "Random Array: ";
sortData(iptr, size);
displayArray(iptr, size);
cout << endl;
sortData(iptr, size);
double median = findMed(iptr, size);
cout << "The median of the array is " << median << endl;
cout << "The number of numbers in the array is " << size << endl;
delete[] iptr;
cout << "Type any key to continue--> ";
_getch();
return 0;
}
//Define randomArray() function
/*This function creates an array of random numbers
of a given size in a given range pointed to by an integer pointer*/
int* randomArray(int size, int range)
{
int* iptr = new int[size]; //Allocate memory for the array
for (int i = 0; i < size; i++)
{
*(iptr + i) = rand() % (range); //Generates a random number 0--range
}
return iptr;
}
//Define displayArray()
void displayArray(int* iptr, int size)
{
for (int i = 0; i < size; i++)
cout << *(iptr + i) << " ";
cout << endl;
}
//Define sortData() function
void sortData(int* iptr, int size)
{
//This function sorts the data set using the selection sort algorithm
int bottom = 0, top = size - 1, min, temp, minPosition;
while (bottom < top)
{
min = *(iptr + bottom); //The initial minimum value is at the bottom of the array
minPosition = bottom; //The initial position in array of minimum value
for (int i = bottom + 1; i <= top; i++) //This loop determines the minimum value in list from bottom to top and its position in the list
{
if (*(iptr + i) < min)
{
min = *(iptr + i);
minPosition = i;
}
}
//Swap bottom with new minimum value
temp = *(iptr + bottom);
*(iptr + bottom) = min;
*(iptr + minPosition) = temp;
bottom++; //Increment bottom to new selection of array
}
}
//Define findMed() function
double findMed(int* iptr, int size)
{
double median = 0.0; //Median of array
int mid = 0; //Mid is the middle number or middle two numbers
if (size % 2 == 0) //If size is an even number
{
mid = (size / 2) - 1;
median = (*(iptr + mid) + *(iptr + (mid + 1))) / 2;
}
else //If size is an odd number
{
mid = (int)(size / 2);
median = *(iptr + mid);
}
return median;
}
|