Monday, November 18, 2013

Selection 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 selectionSort() {
    int x, y, min;
    for (x = 0; x < n; x++) {
        min = x;
        for (y = (x + 1); y < n; y++) {
            if (bil[min] > bil[y]) {
                min = y;
            }
        }
        swap(x, min);
    }
}

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

No comments:

Post a Comment