【发布时间】:2016-04-07 14:57:30
【问题描述】:
我在下面写了选择排序方法。我想保留一般的代码,因为它是一个学校练习,但我知道有更正确的方法可以做到这一点,就像 Linq 一样。 除了只对属性 PersonalNumber 进行排序之外,它还可以很好地工作。我可以看到错误如下:
temp = list[i].PersonalNumber;
list[i].PersonalNumber = list[posMin].PersonalNumber;
list[posMin].PersonalNumber = temp;
有没有办法对列表中每个索引包含的所有属性进行排序?还是我必须为每个属性编写上述代码?一共有三个属性。
完整方法:
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;
}
}
}
【问题讨论】:
-
你可以使用 Linq,它会用简单的标准为你排序列表
-
嗨,我还是个新手。我稍后离开 Linq。我还在学习基础知识。
-
Linq 是你的“朋友”:-p stackoverflow.com/questions/722868/…
-
为什么不交换 Person 对象本身而不是它们的属性呢?
temp = list[i]; list[i] = list[posMin]; list[posMin] = temp; -
@MaxModestoWallin
temp必须是Person,而不是int。