我知道如何对数组进行排序(即冒泡排序),但我不知道如何根据第 n 项对数组进行排序。如果有的话,你能给我一个想法或例子吗?感谢大家的赞赏回答。 @edit:程序如何感知到带零的数字,我的意思是1个程序感知0001或00001 ....?
Example:
2 --> nth digit
4 45 62 1 900 105 --> inputs
输出: 001 004 105 900 045 065
<小时/>void bubble_sort(int iarr[], int num) {
int i, j, k, temp;
printf("\nUnsorted Data:");
for (k = 0; k < num; k++) {
printf("%5d", iarr[k]);
}
for (i = 1; i < num; i++) {
for (j = 0; j < num - 1; j++) {
if (iarr[j] > iarr[j + 1]) {
temp = iarr[j];
iarr[j] = iarr[j + 1];
iarr[j + 1] = temp;
}
}
printf("\nAfter pass %d : ", i);
for (k = 0; k < num; k++) {
printf("%5d", iarr[k]);
}
}
}
最佳答案
简单的回答是,您的比较函数需要查看第 n 位数字而不是整个数字。
因此,如果您最初的比较是这样的:
if (a < b) // handle a before b case
elseif (b < a) // handle b before a case
您需要将其更改为:
aDigit = getNthDigit(a, n);
bDigit = getNthDigit(b, n);
if (aDigit < bDigit) // handle a before b case
elseif (bDigit < aDigit) // handle b before a case
您还必须实现 getNthDigit
,这将涉及整数除法和模运算符。
关于c - 根据第 n 项对数字进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26808259/