[英]My BubbleSort alghorithm doesn't seem to work and I don't know why
I'm trying to sort the specified column of the matrix in descending order, but my sorting algorithm doesn't seem to work and I don't know why.我试图按降序对矩阵的指定列进行排序,但我的排序算法似乎不起作用,我也不知道为什么。
void Prohod(float MAT[][4], int numberOfRows, int givenColumn) {
float temp;
for (int i = 0; i < numberOfRows; i++) {
if (MAT[i][givenColumn] < MAT[i + 1][givenColumn]) {
temp = MAT[i][givenColumn];
MAT[i][givenColumn] = MAT[i + 1][givenColumn];
MAT[i + 1][givenColumn] = temp;
}
}
printf("Given column:%d\n",givenColumn);
}
I tried to apply the BubbleSort algorithm to batch the values, but for some reason it doesn't work.我尝试应用 BubbleSort 算法对值进行批处理,但由于某种原因它不起作用。
I added another for loop for the following element like this:我为以下元素添加了另一个 for 循环,如下所示:
for (int i = 0; i < numberOfRows; i++) {
for (int j = i + 1; j < numberOfRows; j++) {
if (MAT[i][givenColumn] < MAT[j][givenColumn]) {
temp = MAT[i][givenColumn];
MAT[i][givenColumn] = MAT[j][givenColumn];
MAT[j][givenColumn] = temp;
}
}
}
And It works now.它现在有效。
MAT[i + 1]
in your for
loopfor
循环中使用MAT[i + 1]
的元素太过分了for
loop does one full pass at the [column] array.for
循环在 [column] 数组上执行一次完整传递。for
loop that repeats this N times (eg a "pass" counter).for
循环(例如,“通过”计数器)。Here is the improved code:这是改进后的代码:
void
Prohod(float MAT[][4], int numberOfRows, int givenColumn)
{
float temp;
for (int pass = 0; i < numberOfRows; pass++) {
int swap = 0;
// after a single pass, the _last_ element is guaranteed to be correct
// so we can look at one fewer element on each pass
int curcount = (numberOfRows - 1) - pass;
for (int i = 0; i < curcount; i++) {
if (MAT[i][givenColumn] < MAT[i + 1][givenColumn]) {
temp = MAT[i][givenColumn];
MAT[i][givenColumn] = MAT[i + 1][givenColumn];
MAT[i + 1][givenColumn] = temp;
swap = 1;
}
}
// early escape -- no swaps occurred -- all are in sort
if (! swap)
break;
}
printf("Given column:%d\n", givenColumn);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.