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 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
|
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
template <typename T>
void insertionSort(vector<T>& a_value) //vector is used as an implementation of a List
{
int i, j, n = a_value.size(); //i is the pseudo-Code Index and j is the scanIndex
T temp;
// Select List[Index] as element to be inserted into sorted sublist.
// place v[i] into the sublistv[0] ... v[i-1], 1 <= i < n,
// so it is in the correct position
for (i = 1; i < n; i++)
{
// index j scans down list from v[i] looking for correct position to locate temp assigns it to v[j]
j = i;
temp = a_value[ i];
// find where to insert in the sorted sublistand shift elements to right while scanning
//from right-to-left
while ( j > 0 && temp < a_value[ j-1 ])
{
// shift elements up list to make room for insertion
a_value[ j ] = a_value[ j-1];
j--;
}
// the location is found; insert temp
a_value[j] = temp;
}
}
template <typename T>
void fill_vector(ifstream& in_file, vector<T> & v)
{
T a_value;
while (!in_file.eof())
{
in_file >> a_value;
v.push_back(a_value);
}
}
template <typename T>
double median(const vector<T> & v)
{
int length = v.size();
double median;
if(length <= 1)
return v[length];
else if( length % 2 == 0 ) // even
{
median = (v[length/2] + v[(length/2)-1]) / 2;
}
else // odd
{
median = v[length/2];
}
return median;
}
int main() // begin main
{
vector<double> v;
char filename[16];
cout << "Enter a file name: ";
cin >> filename;
cout << endl;
ifstream fin(filename);
if (!fin)
{
cerr << "Could not open the file" << endl;
return 1;
}
fill_vector(fin,v);
cout << "Values entered: ";
for (int p = 0; p < v.size(); p++)
{
cout << v[p] << ",";
}
cout << endl;
insertionSort(v);
cout << "Sorted values: ";
for (int k = 0; k < v.size(); k++)
{
cout << v[k] << ",";
}
cout << endl;
cout << "Median Value: " << median(v) << endl;
system("pause");
} //end main
/*====================OUTPUT==========================
Enter a file name: file.txt
Values entered: 2.3,2,
Sorted values: 2,2.3,
Median Value: 2.15
Press any key to continue . . .
Enter a file name: file.txt
Values entered: 2.3,2,7,8,100,-2,3,2,2.5,19,3,
Sorted values: -2,2,2,2.3,2.5,3,3,7,8,19,100,
Median Value: 3
Press any key to continue . . .
Enter a file name: file.txt
Values entered: 1,2,3,4,5,6,7,8,9,
Sorted values: 1,2,3,4,5,6,7,8,9,
Median Value: 5
Press any key to continue . . .
====================OUTPUT==========================*/
| |