Skip to main content
Logo image

Section 3.11 Examples

We now have the means to implement the examples from [cross-reference to target(s) "sec-simple-algo" missing or not unique] in C.

Example 3.11.1. Number Conversion.

#include <stdio.h>

void print_hex(unsigned word)
{
    unsigned shift = 8 * sizeof(word);
    do {
        shift -= 4;
        unsigned digit = (word >> shift) & 0x0f;
        unsigned ascii = digit + (digit < 10 ? '0' : 'a' - 10);
        putchar(ascii);
    } while (shift != 0);
}
Listing 3.11.2. Number conversion implementation

Example 3.11.3. The Sieve of Eratosthenes.

#include <string.h>

char* eratosthenes(char* table, unsigned n) {
    memset(table, 0, n);
    for (unsigned q = 2; q * q < n; q++) {
        if (table[q] == 0) {
            for (unsigned j = q * q; j < n; j += q)
                table[j] = 1;
        }
    }
    return table;
}
Listing 3.11.4. Sieve of Eratosthenes implementation

Example 3.11.5. Insertion Sort.

#include <assert.h>

static unsigned find(int* arr, unsigned n, int value)
{
    unsigned i = 0;
    while (i < n && arr[i] < value)
        i++;
    return i;
}

static void insert(int* arr, unsigned n, unsigned from, unsigned to)
{
    assert(to <= from);
    int val = arr[from];
    for (unsigned i = to; i <= from; i++) {
        int tmp = arr[i];
        arr[i]  = val;
        val     = tmp;
    }
}

void insertsort(int* arr, unsigned n)
{
    for (unsigned i = 1; i < n; i++) {
        unsigned pos = find(arr, n, arr[i]);
        insert(arr, n, i, pos);
    }
}
Listing 3.11.6. Insertion sort implementation