c - C 中数字数组的排序

标签 c arrays function sorting

// code to sort array of 16 numbers, but output isnt quite correct.
// must use pointers to array addresses
// final output is -451 993 384 201 89 77 38 28 16 12 7 1 0 -2 -5 -17
// as you can see -451 isn't in the right place.

输出

-451 7 993 1 0 16 -5 12 89 28 77 384 -2 38 -17 201

-451 -17 993 7 1 16 0 12 89 28 77 384 -2 38 -5 201

-451 993 -17 7 1 16 0 12 89 28 77 384 -2 38 -5 201

-451 993 7 -17 1 16 0 12 89 28 77 384 -2 38 -5 201

-451 993 7 1 -17 16 0 12 89 28 77 384 -2 38 -5 201

-451 993 16 7 1 -17 0 12 89 28 77 384 -2 38 -5 201

-451 993 16 7 1 0 -17 12 89 28 77 384 -2 38 -5 201

-451 993 16 12 7 1 0 -17 89 28 77 384 -2 38 -5 201

-451 993 89 16 12 7 1 0 -17 28 77 384 -2 38 -5 201

-451 993 89 28 16 12 7 1 0 -17 77 384 -2 38 -5 201

-451 993 89 77 28 16 12 7 1 0 -17 384 -2 38 -5 201

-451 993 384 89 77 28 16 12 7 1 0 -17 -2 38 -5 201

-451 993 384 89 77 28 16 12 7 1 0 -2 -17 38 -5 201

-451 993 384 89 77 38 28 16 12 7 1 0 -2 -17 -5 201

-451 993 384 89 77 38 28 16 12 7 1 0 -2 -5 -17 201

-451 993 384 201 89 77 38 28 16 12 7 1 0 -2 -5 -17

总交换次数:68

#include <stdio.h>

#define N 16

int xchg();

int main() {
    int numbers[16] = {7, 1, 993, -5, 0, 16, -451, 12, 89, 28, 77, 384, -2, 38, -17, 201}; 
    int cntr, cntr2, cntr3;
    int chgNum;

    for(cntr = 0; cntr < N; cntr++){
        for(cntr2 = 1; cntr2 < N; cntr2++){
            chgNum += xchg(&numbers[cntr], &numbers[cntr2]);
        }
        for(cntr3 = 0; cntr3 < N; cntr3++){
            if(cntr3 == 15){
                printf("%d", numbers[cntr3]);
            }
            else {
                printf("%d ", numbers[cntr3]);
            } 
        }

        printf("\n");


    }
    printf("total exchanges: %d\n", chgNum);
    return 0;
}

int xchg(int *p1, int *p2) {
    int tmp = 0;
    if(*p2 < *p1){
        tmp = *p1;
        *p1 = *p2;
        *p2 = tmp;
        return 1;
    }
    else {
        return 0;
    }
}

最佳答案

您需要更改main中的循环。

for(cntr2 = cntr+1; cntr2 < N; cntr2++){

您可能还想检查 xchg 是否为您提供升序/降序排序顺序,或者是否需要反转交换条件。

另外:您忘记将 chgNum 初始化为零。

关于c - C 中数字数组的排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26869268/

相关文章:

缓存模拟器::命中与未命中问题

C 程序跳过 Main 中的 scanf 请求

javascript - 检查每个数组值是否为 NaN

javascript - 用于搜索实现的多级数组过滤器

javascript - 无法打印所有数组元素

ios - 在 Swift 中按下特定的键盘按钮

c++ - 整数乘以有理数没有中间溢出

javascript - 'self.fn.apply(self, message)' 和 'self.fn(message)' 之间有什么不同,为什么使用第一种方法?

javascript - 有人可以解释这个功能吗?

c - 使用指向非结构类型的不透明指针