Bubblesort Muster

Reading time ~1 minute

Framework für Bubblesort

#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>

#define LEN 128

extern  void bs   (int64_t, int32_t*);
        void bs_c (int64_t, int32_t*);
        void print(int64_t, int32_t*);

int main(int argc, char** argv)
{
    int32_t buffer[LEN];
    int32_t len = argc - 1;

    for (int64_t i = 1; i < argc; i++)
        buffer[i-1] = atoi(argv[i]);

    print(len, buffer);
    bs(len, buffer);
    print(len, buffer);

    return EXIT_SUCCESS;
}

void bs_c(int64_t len, int32_t* buffer)
{
    for(int64_t i = len - 1; i > 0; i--)
        for (int64_t j = 0; j < i; j++)
            if (buffer[j] > buffer[j+1])
            {
                int64_t tmp = buffer[j];
                buffer[j]   = buffer[j+1];
                buffer[j+1] = tmp;
            }
}

void print(int64_t len, int32_t* buffer)
{
    printf("(");
    for (int64_t i = 0; i < len -1; i++)
        printf("%"PRIi32", ", buffer[i]);
    printf("%"PRIi32")\n", buffer[len-1]);
}

Bubblesort in NASM

; rdi: length of array, rsi: pointer to array
section .text
global bs
bs:
; init
xor rax, rax
mov rcx, rdi
inc rcx

_outer:
    dec rcx
    cmp rcx, 1
    jle _exit
    xor r8 , r8

_inner:
    cmp r8 , rcx
    jge _outer
    mov r9 , [rsi+r8*8]
    mov r10, [rsi+r8*8+8]
    cmp r9 , r10
    jle _nochange
    mov [rsi+r8*8]  , r10
    mov [rsi+r8*8+8], r9

_nochange:
    inc r8
    jmp _inner

_exit:
ret