Skip to content

Instantly share code, notes, and snippets.

@hackeris
Last active August 13, 2021 11:37
Show Gist options
  • Save hackeris/bd3ed3bfa3c1427f5a2d099b5fe80529 to your computer and use it in GitHub Desktop.
Save hackeris/bd3ed3bfa3c1427f5a2d099b5fe80529 to your computer and use it in GitHub Desktop.
bubble sort in asm
bubble sort in asm
extern bubble_sort
; rdi: a[]
; rsi: n
bubble_sort:
mov eax, 0 ; i
mov ebx, 0 ; j
sub esi, 1 ;
loop_outer:
cmp esi, eax
je outer_end
outer_body:
mov ebx, esi
loop_inner:
mov ecx, eax
cmp ecx, ebx
je inner_end
inner_body:
lea rcx, [rdi + rbx * 4] ; a[j]
mov rdx, rcx
sub rdx, 4 ; a[j-1]
mov r8d, dword [rcx]
mov r9d, dword [rdx]
cmp r8d, r9d
jg inner_continue
mov dword [rcx], r9d
mov dword [rdx], r8d
inner_continue:
sub ebx, 1
jmp loop_inner
inner_end:
outer_continue:
add eax, 1
jmp loop_outer
outer_end:
ret
#include <stdio.h>
void bubble_sort(int a[], int n);
int main() {
int a[] = {9,4,5,3,1,7,8,2,0,6};
bubble_sort(a, 10);
for(int i = 0; i < 10; i += 1) {
printf("%d\n", a[i]);
}
return 0;
}
main: main.o bubble.o
gcc -g main.o bubble.o -o main
main.o: main.c
gcc -g -c main.c -o main.o
bubble.o: bubble.asm
nasm -g -felf64 bubble.asm -o bubble.o
clean:
rm *.o main
.PHONY : clean
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment