usesort.cc From Astrachan pp 534-535 ------------------------------------ #include #include "vector.h" #include "worditer.h" // Owen Astrachan, 7/30/95 // illustrates templated function for sorting // reads file of words, sorts words, prints words template void Sort(Vector & a, int numElts) // precondition: a contains numElts ints // postcondition: elements of a are sorted in non-decreasing order { int j,k,minIndex; Type temp; for(k=0; k < numElts - 1; k++) { minIndex = k; // smallest item from k to end of a for(j=k+1; j < numElts; j++) { if (a[j] < a[minIndex]) { minIndex = j; // new smallest item, remember where } } temp = a[k]; // swap smallest item and k-th item a[k] = a[minIndex]; a[minIndex] = temp; } } int main() { int SIZE = 2000; // size of wordlist WordStreamIterator iter; // to iterator over file Vector list(SIZE); // to store words int numWords = 0; // to count words string filename; int k; cout << "file name: "; cin >> filename; iter.Open(filename); for(iter.First(); ! iter.IsDone(); iter.Next()) // read words { if (numWords >= SIZE) { SIZE *= 2; list.SetSize(SIZE); } list[numWords] = iter.Current(); numWords++; } Sort(list,numWords); // sort words for(k=0; k < numWords; k++) // print words { cout << list[k] << endl; } return 0; }