以下代码对二维指针数组的一列进行排序:
void sort(int** rowReferences, int rowCount, int colCount, int sortColumn) {
int pos, lower, temp;
for (int p = 0; p < rowCount; p++)
{
pos = p;
lower = rowReferences[p][sortColumn];
for (int j = p + 1; j < rowCount; j++) {
if (rowReferences[j][sortColumn] < lower) {
pos = j;
lower = rowReferences[j][sortColumn];
}
temp = rowReferences[p][sortColumn];
rowReferences[p][sortColumn] = rowReferences[pos][sortColumn];
rowReferences[pos][sortColumn] = temp;
}
}
}
它适用于大多数情况,但它对某一列并不是很正确。
列值按此顺序排列:2,0,-1,1,3
sort函数在显示:-1,0,2,1,3
后返回此顺序正如您所看到的,排序适用于前两个值,但在此之后会分解。如何修改选择排序以在此实例中工作?
编辑* PaulMcKenzie慷慨提供的最小,完整,可验证的例子:http://ideone.com/lXHFHE
答案 0 :(得分:1)
这部分代码
temp = rowReferences[p][sortColumn];
rowReferences[p][sortColumn] = rowReferences[pos][sortColumn];
rowReferences[pos][sortColumn] = temp;
必须超出范围:)
最终代码:
void sort(int** rowReferences, int rowCount, int colCount, int sortColumn) {
int pos, lower, temp;
for (int p = 0; p < rowCount; p++)
{
pos = p;
lower = rowReferences[p][sortColumn];
for (int j = p + 1; j < rowCount; j++) {
if (rowReferences[j][sortColumn] < lower) {
pos = j;
lower = rowReferences[j][sortColumn];
}
}
temp = rowReferences[p][sortColumn];
rowReferences[p][sortColumn] = rowReferences[pos][sortColumn];
rowReferences[pos][sortColumn] = temp;
}
}