I’m fairly new to c++ programming and I need help with the coding to sort the numbers from a text file into ascending order so I can take the median of it, but I’m not sure how to do that.
Here is my code so far:
//Create a Vector to hold a set of exam scores.Write a program to do the following tasks: 1. Read exam scores into a vector from Scores.txt
//2. Display scores in rows of five(5) scores.
//3. Calculate average score and display.
//4. Find the median score and display.
//5. Compute the Standard Deviation and display
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
int main ()
{ const int array_size = 36; // array size
int numbers[array_size]; //array with 36 elements
int count = 0;
int column_count = 5;
ifstream inputfile; //input file into stream object
//open file
inputfile.open("Scores.txt");
//read file
while (count < array_size && inputfile >> numbers[count])
count++;
//close file
inputfile.close();
//display numbers read
for (count = 0; count < array_size; count++) {
cout << numbers[count] << " ";
if ( count % column_count == column_count - 1 ) {
cout << "\n";
}
}
//find the average
double average; //average
double total = 0; //initialize accumulator
cout << "\nAverage:\n";
for (count = 0; count < array_size; count++)
total += numbers[count];
average = total/array_size;
cout << average << " ";
cout << endl;
//find the median
std::sort(numbers.begin(), numbers.end(), std::greater<int>());
system ("pause");
return 0;
}
Thanks in advance!
You probably copied this line from somewhere without understanding what it really means:
Since you are using regular arrays, the first argument is a pointer to the first position in the array. The second argument is a pointer to one past the last element in the array. The third argument indicates in which direction the array should be sorted (in your case, you want to find the median, so the direction doesn’t matter). For your array called numbers with a length of
array_size, the new function call is rewritten as:When passing arrays to functions, they decay into pointers on their own. So, you don’t need to use the
&operator. The function call can be simplified to:The purpose for sorting the data in this situtation is to find the median. Regardless of sorting the array ascending or descending, the average of the middle element(s) will be the same. If you had further use for the array where it needs to be sorted in ascending order, change the third argument to
std::less<int>()(or remove it completely). It will cause the array to be sorted in ascending order.