Created
July 23, 2023 01:22
-
-
Save phoemur/6fd223d58ff33eee9990d77e854557ab to your computer and use it in GitHub Desktop.
Quicksort example in x86_64 Assembly - Linux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; Quicksort example in x86_64 Assembly - Linux | |
; Assembler: NASM | |
; Fernando B. Giannasi - jul/2023 | |
section .data | |
DATA dq 1, 9, 2, 8, 3, 7, 4, 6, 5, 0, 70, 69, 68, 67, 66, 65, 1, 9, 2, 8, 3, 7, 4, 6, 5, 0, 70, 69, 68, 67, 66, 65, 1, 9, 2, 8, 3, 7, 4, 6, 5, 0, 70, 69, 68, 67, 66, 65 | |
DATA_LEN equ $ - DATA | |
section .bss | |
buffer resb DATA_LEN + 2 | |
section .text | |
global _start | |
_start: | |
; Print original array | |
call _printbuf | |
; get indexes | |
xor rdi, rdi ; low | |
mov rsi, DATA_LEN | |
sub rsi, 8 ; high | |
; call quicksort | |
push rdi | |
push rsi | |
call _quicksort | |
; Print sorted array | |
call _printbuf | |
; Exit Success | |
mov rax, 60 | |
mov rdi, 0 | |
syscall | |
; input: | |
; low, high (indexes) on the stack | |
; DATA is pointer to qword (int64) array | |
_quicksort: | |
pop r9 ; return address | |
pop rsi ; high | |
pop rdi ; low | |
push r9 ; recover it | |
cmp rdi, rsi ; base case, return | |
jge .localret | |
; Partition | |
mov rdx, qword [DATA + rsi] ; pivot element at the end | |
mov rcx, rdi | |
sub rcx, 8 ; index of smaller element | |
mov r9, rdi ; int j = low | |
mov r10, rsi | |
sub r10, 8 ; high - 1 | |
.partitionloop: | |
mov rbx, qword [DATA + r9] ; current element | |
cmp rbx, rdx ; compare with pivot | |
jg .slip | |
add rcx, 8 ; increment index of smaller element | |
;swap | |
mov r11, qword [DATA + rcx] | |
mov r12, qword [DATA + r9] | |
mov [DATA + rcx], r12 | |
mov [DATA + r9], r11 | |
.slip: | |
add r9, 8 | |
cmp r9, r10 | |
jle .partitionloop | |
add rcx, 8 | |
; swap | |
mov r11, qword [DATA + rcx] | |
mov r12, qword [DATA + rsi] | |
mov [DATA + rcx], r12 | |
mov [DATA + rsi], r11 | |
; quicksort both halves | |
push rdi | |
sub rcx, 8 | |
push rcx | |
add rcx, 16 | |
push rcx | |
push rsi | |
call _quicksort | |
call _quicksort | |
.localret: | |
ret | |
; convert DATA (int64) array to ASCII buffer and print | |
_printbuf: | |
xor rcx, rcx | |
mov rsi, DATA | |
mov rdi, buffer | |
cld | |
.loopi: | |
mov rax, [rsi] | |
add rax, 48 | |
mov [rdi], rax | |
add rcx, 8 | |
add rsi, 8 | |
inc rdi | |
cmp rcx, DATA_LEN | |
jl .loopi | |
mov rax, 10 | |
stosb | |
mov rax, 0 | |
stosb | |
mov rax, 1 | |
mov rdi, 1 | |
mov rsi, buffer | |
mov rdx, DATA_LEN + 2 | |
syscall | |
ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment