Monday, November 18, 2013

Insertion Sort In C

#include <stdio.h>

int n = 7;
int bil[] = {5, 3, 8, 4, 7, 2, 1};

void swap(int first, int second) {
    int tampung = bil[first];
    bil[first] = bil[second];
    bil[second] = tampung;
}

void insertionSort() {
    int x, y, stop, tampung;
    for (x = 1; x < n; x++) {
        stop = x;
        for (y = (x - 1); y >= 0; y--) {
            if (bil[x] < bil[y]) {
                stop = y;
            }
        }
        tampung = bil[x];
        for (y = x - 1; y >= stop; y--) {
            swap(y, (y + 1));
        }
        bil[stop] = tampung;
    }
}

int main() {
    insertionSort();
    int x;
    for (x = 0; x < n; x++) {
        printf("%d ", bil[x]);
    }
    return 0;
}


No comments:

Post a Comment