【发布时间】:2014-06-05 23:31:57
【问题描述】:
我的老师布置了一些事情,如果不使用qsort,我似乎不知道该怎么做。我们得到一个 2x3 数组,他希望我们将每一行从最小值排序到最大值。我不允许将qsort用于学习目的;在我看来,这很难。
这是我目前所拥有的;目前,该程序崩溃。我假设这是因为当它到达第三列时,第四列[j+1] 中没有任何内容,所以它返回一个错误。
#include "stdafx.h"
#include <stdio.h>
int main() {
int x[2][3] = { { 2, 3, -1 }, { 0, -3, 5 } }; //2x3 matrix; 2 rows, 3 columns
void sortMinMax(int b[][3], int numRow, int numColumn); //function prototype
sortMinMax(x, 2, 3);
return 0;
}
void sortMinMax(int a[][3], int numRow, int numColumn) {
for (int i = 0; i < numRow; i++) {
for (int j = 0; j < numColumn - 1; j++) {
if (a[i][j + 1] < a[i][j]) { //swap values if the next number is less than the current number
int temp = a[i][j];
a[i][j] = a[i][j + 1];
a[i][j + 1] = temp;
}
printf("%i\t", a[i][j]);
}
printf("\n");
}
return;
}
感谢所有帮助!
【问题讨论】:
-
您发现了一个错误,为什么不修复它并再次测试呢?即 for (int j = 0; j
-
你老师要你自学排序算法,google一下常用的排序算法,找一个简单的,看看伪代码实现一下。
-
如果大小是恒定的(始终是 2x3 数组),为什么要在函数中使用大小参数?
-
您可能会发现编写一个对单行排序的函数,然后为每一行调用它会更容易。
-
那么你的外循环会超出范围,从修复它开始。而对于内部循环,当您进行最后一次迭代时,您认为
j + 1会给您带来什么价值?
标签: c sorting multidimensional-array