I've written the the selection sort method beneath. I would like to retain the code in general as it's a school exercise, but I understand that there are more correct ways to do it, as with Linq. It works well besides that it only sorts the property PersonalNumber. I can see where the error is the following:
temp = list[i].PersonalNumber;
list[i].PersonalNumber = list[posMin].PersonalNumber;
list[posMin].PersonalNumber = temp;
Is there any way to sort all of the properties contained for each index in the list? Or do I have to write the above code for each property? There are three properties in total.
Full method:
public static void SelectionSort(List<Person> list) {
// With this method the Person list is sorted in ascending order.
//posMin is short for position of min
int posMin, temp;
for (int i = 0; i < list.Count - 1; i++) {
posMin = i;//Set posMin to the current index of array
for (int j = i + 1; j < list.Count; j++) {
if (list[j].PersonalNumber < list[posMin].PersonalNumber) {
//posMin will keep track of the index that min is in, this is needed when a swap happens
posMin = j;
}
}
//if pos_min no longer equals i than a smaller value must have been found, so a swap must occur
if (posMin != i) {
temp = list[i].PersonalNumber;
list[i].PersonalNumber = list[posMin].PersonalNumber;
list[posMin].PersonalNumber = temp;
}
}
}