Selection Sort an Array - C Data Structure

C examples for Data Structure:Sort

Description

Selection Sort an Array

Demo Code

#include <stdio.h>

#define MaxNumbers 10/* w w  w. ja v a2 s. com*/

void selectionSort(int [], int, int);
int getSmallest(int[], int, int);

int main() {
    int num[] = {10, 3, 5, 4, 6, 8, 12, 7, 13, 17};
    int n = 10;
    selectionSort(num, 0, n-1);

    for (int i = 0; i < n; i++) 
       printf("%d \n", num[i]);

}
void selectionSort(int list[], int lo, int hi) {

    void swap(int[], int, int);
    for (int i = lo; i < hi; i++) {
        int s = getSmallest(list, i, hi);
        swap(list, i, s);
    }
}
int getSmallest(int list[], int lo, int hi) {
    int small = lo;
    for (int i = lo + 1; i <= hi; i++)
        if (list[i] < list[small]) small = i;
    return small;
}
void swap(int list[], int i, int j) {
    int hold = list[i];
    list[i] = list[j];
    list[j] = hold;
}

Related Tutorials