------------------------------------------------------------------------------
MC logo
Integer Select Sort
[^] Code Examples
------------------------------------------------------------------------------
<<Character Histogram Generator simintsrc.c Integer Quick Sort>>
#include <stdio.h>

/* 
 * Program to read a list of integers from standard input and print them in
 * sorted order.  This uses a simple selection sort.
 *
 * Author: Tom Bennet
 */

/* 
 * Swap function for sorting.
 */
void swap(int *a, int *b)
{
        int tmp;                                /* Exchange temp value. */

        tmp = *a;
        *a = *b;
        *b = tmp;       
}

/* 
 * Sort the array.  It receives a pointer to the start of the data and the
 * number of items.
 */
void sort(int *data, int size)
{
        int minloc;                     /* Loc of minimum. */

        for(minloc = 0; minloc < size - 1; ++minloc) {
                int scan;
                for(scan = minloc + 1; scan < size; ++scan)
                        if(data[minloc] > data[scan])
                                swap(&data[minloc], &data[scan]);
        }
}

/*
 * Main program.  Reads the integers into an array, sorts them, and
 * prints them out.
 */
#define MAX_NUM_INTS    100
int main()
{
        int ints[MAX_NUM_INTS];         /* Where the numbers are. */
                
        /* Read them in. */
        int i;
        for(i = 0; i < MAX_NUM_INTS && scanf("%d", &ints[i]) == 1; ++i);
        int numints = i;

        /* Sort them. */
        sort(ints, numints);

        /* Print them. */
        printf("==================\n");
        for(i = 0; i < numints; ++i)
                printf("%d\n", ints[i]);
        printf("==================\n");
}

This program simply sorts a list of input integers. It implements a selection sort. The sort function uses the common C idiom of taking an array name (pointer to the first item) and the number of positions to operate on.
Reading: pp. 48-49
<<Character Histogram Generator Integer Quick Sort>>