I'm doing homework that asks me to sort names alphabetically(both ascending and descending order) using selection sort. So there is a data file that has all the names saved in it and it's called "names.dat". The names are saved like:
Collins, Bill
Smith, Bart
.
.
.
Holland, Beth
So what I did was reading the data from the file and saved them in a 2D array. Then I wrote a void function that sorts the names in the ascending order. I think I understand how the selection sort method works, but I don't seem to understand how to work the 2D array around... Eventually i need to display the first names sorted alphabetically without sorting last names (and I'm just going to assume that the names are saved in the form of "first, last") so for example, after sorting the display will look like : "Collins, Bill /n Holland, Beth /n, ..., Smith, Bart"
It took me many hours to understand the selection sort and write it in the program, but now I'm facing the issue of not knowing how to manipulate the array... I would really appreciate your help! I will post my program here.
#include<iostream>
#include<string>
#include<cstring>
#include<iomanip>
#include<fstream>
using namespace std;
const int SIZE = 20;
void setAscendingSort(string [][], int);
//void setDescendingSort();
void displayArray(string [][]);
int main()
{
string first, last, NAMES[SIZE][2];
ifstream infile;
infile.open("names.dat");
int i = 0;
while (!infile.eof())
{
infile >> first;
NAMES[i][0] = first;
cout << NAMES[i][0] << " ";
if(infile.eof())
{
cout << endl;
break;
}
infile >> last;
NAMES[i][1] = last;
cout << NAMES[i][1] << " " << endl;
++i;
}
setAscendingSort(NAMES, SIZE);
cout << "The volues after the selection sort is performed are:" << endl;
displayArray(NAMES, SIZE);
return 0;
}
void displayArray(int array[][], int elems)
{
for (int count = 0; count < elems; count++)
cout << array[count][0] << " ";
cout << endl;
}
void setAscendingSort(string array[][], int elems)
{
int seek = 0;
int minCount; //location of smallest value found
int minValue; //holds the smallest value found
for (seek = 0; seek < (elems - 1); seek++)
{
minCount = seek;
minValue = array[seek][0];
for (int index = seek + 1; index < elems; index++)
{
if (array[index][0] < minValue)
{
minValue = array[index][0];
minCount = index;
}
}
array[minCount][0] = array[seek];
array[seek] = minValue;
}
}
I mean when I wrote it, it completely made sense to me but I'm a novice to programming after all. :(