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.
I added another for loop for the following element like this:
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
loop does one full pass at the [column] array.for
loop that repeats this N times (eg a "pass" counter).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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.