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
|
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
void msHeap(string ar[], string arC[], int i, int n)
{
int k = i * 2 + 1;
while (k < n)
{
if(k + 1 < n && arC[k] < arC[k+1])k++;
if(k + 1 < n && ar[k] < ar[k+1])k++;
if (arC[i] < arC[k])swap(arC[i], arC[k]);
if (ar[i] < ar[k])swap(ar[i], ar[k]);
k = i++ * 2 + 1;
}
}
void mHeap(string ar[], int i, int n)
{
int k = i * 2 + 1;
while (k < n)
{
if(k + 1 < n && ar[k] < ar[k+1])k++;
if (ar[i] < ar[k])swap(ar[i], ar[k]);
k = i++ * 2 + 1;
}
}
// heapsort - largest at the top
// build the heap
void hcSort(string ar[], string arC[], int n)
{
int i = n / 2;
while(i-- > 0) msHeap(ar, arC, i, n);
while(n-- > 0)
{
swap(arC[0], arC[n]);
swap(ar[0], ar[n]);
mHeap(arC, 0, n);
mHeap(ar, 0, n);
}
}//sort the heap
// heapsort - largest at the top
// build the heap
void hSort(string ar[], int n)
{
int i = n / 2;
while(i-- > 0) mHeap(ar, i, n);
while(n-- > 0)
{
swap(ar[0], ar[n]);
mHeap(ar, 0, n);
}
}//sort the heap
string rmSpc(string stringIn)
{
size_t pos = 0;
bool spacesLeft = true;
while(spacesLeft)
{
pos = stringIn.find(" ");
if(pos != string::npos)stringIn.erase(pos, 1);
else spacesLeft = false;
}
return stringIn;
}//remove spaces
int main()
{
string line, dash("-"), ar[200], arC[200];
int l, len = 0, t = 0;
ifstream heap ("Universities.c");
if(heap.is_open())
{
while(!heap.eof())
{
getline(heap,line);
ar[t] = line;
line = rmSpc(line);
arC[t] = line.substr(line.find_last_of(dash) + 1);
t++;
}
}
hSort(ar, t);
for(l = 0; l < t; l++)cout << ar[l] << endl;
cout << "-------------------------------------------------------------------" << endl;
cout << "Now this Program will print out the Universities according to city:" << endl;
cout << "-------------------------------------------------------------------" << endl;
hcSort(ar, arC, t);
for(l = 0; l < t; l++)cout << arC[l] << endl;
}
|