Hey guys,
I know how to use selection sort with a one dimensional array, but I can't figure out how to change it so that it will work with my two dimensional array. My program assignment requires me to write a list of first and last names from a file into a two dimensional array and then sort them by last name using selection sort. I'm also having problems outputting the array so that one row (a first name and a last name) displays on one line. In case anyone needs to know I'm using Visual Studio 2015.
Thanks for any help.
Whenever you have multi-dimensional data i.e. an object with various attributes like first name, last name, age, gender, IQ, etc it helps to define a custom data type for the object and then there are at least 4 ways you can sort by any one of the attributes, in your case last name:
(a) overloading operator < for the custom data type as this is the default comparator used by std::sort
(b) writing your custom comparator and passing it to std::sort through (i) lambda function, (ii) constructing a function object or (iii) using a named function object. The last 2 methods require a further definition of a comparison struct.
Confusing? Well let's see some actual code:
As @gunnerfunner pointed out, the coding would probably be a lot simpler if you had an array of Person objects that you sorted on one attribute (data member), i.e. lastName.
However, let's assume that you want to keep your multi-d array form. (Parallel arrays for firstName[] and lastName[] instead of second indices 0 and 1 would work similarly).
In void selectionSort(string arrayOfName[ROWS][COLUMNS], int numberOfNamesInArray)
you correctly pass a 2-d array arrayOfName[ROWS][COLUMNS].
Then, however, you revert to 1-d arrays: minValue = arrayOfName[startScan];
and so on, throughout the rest of your function.
If you keep your array structure (your decision, note) and the sort order is done on the lastname, which I assume is the second item, then this line should be minValue = arrayOfName[startScan][1];
Note, however, that to do the swaps of both parts of the name later you will also have to store the first name as well, even though it isn't being used for sorting; say, declare a string variable minFirst and minFirst = arrayOfName[startScan][0];
Check every occurence of arrayOfName in your function and make sure that it has the correct number of [].
In displayArray you don't need the inner j loop - there are only 2 columns, [0] and [1]. Just replace the j loop with cout << arrayOfName[i][0] << " " << arrayOfName[i][1] <<endl;
I reiterate, this is if you want to keep your 2-d array form (or the equivalent parallel-array form with first names and last names in separate arrays). @gunnerfunner's approach of having arrays of Person objects makes for much simpler code, even if you aren't allowed, or don't want to, follow up his use of the standard library sorting functions.