quinta-feira, 21 de outubro de 2010

The 3 simple sort algorithms

/*    Bubble Sort    */
void
bsort (int ar[], int len)
{
    int control = 1, i, tmp;
    while (control--) {
        for (i = 0; i < len - 1; i++) 
            if (ar[i] > ar[i + 1]) {
                tmp = ar[i], ar[i] = ar[i + 1], ar[i + 1] = tmp;
                control = 1;
            }
    }
}

/*    Inserction Sort    */
void
isort (int ar[], int len)
{
    int i, j, tmp;
    for (i = 1; i < len; i++, ar[j + 1] = tmp) 
        for (j = i -1, tmp = ar[i]; j >= 0 && ar[j] > tmp; j--)
            ar[j + 1] = ar[j];
}

/*    Selection Sort    */
void
ssort (int ar[], int len)
{
    int i, j, lesser, tmp, at;
    for (i = 0; i < len - 1; 
         tmp = ar[i], ar[i] = lesser, ar[at] = tmp, i++)
        for (j = i + 1, lesser = ar[i], at = i; j < len; j++) 
            if (lesser > ar[j]) 
                lesser = ar[j], at = j;
}
tested at http://codepad.org/3Co4Qipn

Nenhum comentário:

Postar um comentário