1

i have implemented insertion algorithm in c programming language, but i have faced a little problem when tried to extend it to both increasing and decreasing order, the problem is about that a little piece of code is repeat :

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;
    }
}

there is a ways to do so the for statement and a[j+1] = arr[j] inside the for will be written only one time?

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

And what about a little change in your constants?

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;
    } 
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.