c - 实现插入算法

时间:2014-07-17 00:24:57

标签: c algorithm insertion-sort

我已经在c编程语言中实现了插入算法,但是当我尝试将它扩展到递增和递减顺序时,我遇到了一个小问题,问题是关于一小段代码重复:

typedef int order_t;

#define INCREASING  0
#define DEACREASING 1

extern void insertion_sort(int *const arr, size_t arr_size, order_t order) {
    register size_t i, j;
    register int key;

    for(i = 1; i < arr_size; ++i) {
        key = arr[i];

        if(order == INCREASING) 
            for(j = i - 1; j >= 0 && arr[j] > key; --j) {
                arr[j+1] = arr[j];
            }
        else {
            for(j = i - 1; j >= 0 && arr[j] < key; --j) {
                arr[j+1] = arr[j];
            }
        }

        arr[j+1] = key;
    }
}

有一种方法可以这样做for语句和for中的[j + 1] = arr [j]只能写一次吗?

2 个答案:

答案 0 :(得分:3)

for(i = 1; i < arr_size; ++i) {
    key = arr[i];

    for(j = i - 1; j >= 0 && (order == INCREASING ? (arr[j] > key) : (arr[j] < key)) ; --j) {
         arr[j+1] = arr[j];
    }

    arr[j+1] = key;
}

答案 1 :(得分:0)

你的常数有点变化怎么样?

typedef int order_t;

#define INCREASING  (+1)
#define DEACREASING (-1)

extern void insertion_sort(int *const arr, size_t arr_size, order_t order) {
    register size_t i, j;
    register int key;

    for(i = 1; i < arr_size; ++i) {
        key = arr[i];

        for(j = i - 1; j >= 0 && ((arr[j] - key) * order < 0); --j) {
            arr[j+1] = arr[j];
        }

        arr[j+1] = key;
    } 
 }