names.dat
Collins, Bill
Smith, Bart
Michalski, Mel
Griffin, Jim
Sanchez, Manny
Rubin, Sarah
Taylor, Tyrone
Johnson, Jill
Adams, Andrew
Moreno, Juan
Wolfe, Bill
Whitman, Jean
Moretti, Bella
Wu, Jeff
Patel, Renee
Harrison, Rose
Smith, Cathy
Conroy, Patrick
Kelly, Sean
Holland, Beth

#include<iostream>
#include<fstream>
#include<cctype>
using namespace std;
void read_names(string names[],ifstream& infile,int& index);
void selection_sort(string names[],int size);
void print_names(string names[],int size);

int main()
{
ifstream infile("names.dat");
if(!infile)
{
cout <<"unable to open file..so exiting from program.." << endl;
}
int index = 0;
string array[100];
read_names(array, infile, index);
selection_sort(array,index);

print_names(array,index);
//system("pause");
return 0;
}
.
void read_names(string names[],ifstream& infile,int& index)
{
   index = 0;
   infile >> names[index];
   while(!infile.eof())
   {
       index++;
       infile >> names[index];
   }
}
void selection_sort(string names[],int size)
{
   for(int i=0; i<=size-2; i++)
   {
       int smallpos = i;
       for(int j=i; j<=size-1; j++)
       {
           if(names[j].compare(names[i])<0)
           smallpos = j;
       }
       if(smallpos!=i)
       {
           string temp = names[smallpos];
           names[smallpos] = names[i];
           names[i] = temp;
       }
   }
}
void print_names(string names[],int size)
{
   for(int i=0; i<size; i++)
   {
   cout << names[i] << " ";
   }
   cout << endl;
}

try using a temporary file to store the ascending order and then display it. So that you can quit using array names[]

Edited 2 Years Ago by sanjulovers

Since this is C++, why are you building your own sort routine? Either use C's qsort (with an appropriate comparison function), and then simply walk the array and output the names, or for a purely C++ approach, you can use a map with the key being the lastname,firstname and the value being same thing, insert the name pairs into the map, and then simply iterate through the map and output the key data. Unfortunately, the STL doesn't have a sorted array type which would be less clunky than using a map, though you could simply use a NULL value for each entry since it is the sorted key you are interested in.

Edited 2 Years Ago by rubberman

This article has been dead for over six months. Start a new discussion instead.