Skip to content

Instantly share code, notes, and snippets.

@PoomSmart
Created December 28, 2018 08:23
Show Gist options
  • Save PoomSmart/cf42dc95a323779dd2b977cb8b7939f9 to your computer and use it in GitHub Desktop.
Save PoomSmart/cf42dc95a323779dd2b977cb8b7939f9 to your computer and use it in GitHub Desktop.
Shortest Code to Sort 3 Numbers known to man?
%include "asm_io.inc"
extern _printf
segment data align=4 class=data use32
EnterOne db "Enter number 1: ", 0
EnterTwo db "Enter number 2: ", 0
EnterThree db "Enter number 3: ", 0
FormattedAnswer db "%d %d %d", 0
segment bss align=4 class=bss use32
_a resd 1
_b resd 1
_c resd 1
segment text align=1 class=code use32
global _main
_main:
enter 0, 0 ; setup routine
pusha
enter_number_one:
mov eax, EnterOne
call print_string ; printf("Enter number 1: ");
call read_int ; scanf("%d", &a);
mov [_a], eax
enter_number_two:
mov eax, EnterTwo
call print_string ; printf("Enter number 2: ");
call read_int ; scanf("%d", &b);
mov [_b], eax
enter_number_three:
mov eax, EnterThree
call print_string ; printf("Enter number 3: ");
call read_int ; scanf("%d", &c);
mov [_c], eax
load:
mov eax, [_a]
mov ebx, [_b]
mov ecx, [_c]
move1:
cmp eax, ebx
jle move2
xchg eax, ebx
move2:
cmp eax, ecx
jle move3
xchg eax, ecx
move3:
cmp ebx, ecx
jle print_result
xchg ebx, ecx
print_result:
push ecx
push ebx
push eax
push FormattedAnswer
call _printf
add esp, 10h
call print_nl
popa
mov eax, 0
mov ebx, 0
mov ecx, 0
leave
ret
#include <stdio.h>
inline void xchg(void *v1, void *v2)
{
__asm__ (\
"movl %0, %%eax\n"\
"movl %1, %%ebx\n"\
"xchgl %%ebx, %%eax\n"\
"movl %%eax, %0\n"\
"movl %%ebx, %1\n"\
: : "r"(v1), "r" (v2));
}
int main()
{
int a, b, c;
enter_number_one:
printf("Enter number 1: ");
scanf("%d", &a);
enter_number_two:
printf("Enter number 2: ");
scanf("%d", &b);
enter_number_three:
printf("Enter number 3: ");
scanf("%d", &c);
move1:
if (a > b)
xchg(a, b);
move2:
if (a > c)
xchg(a, c);
move3:
if (b > c)
xchg(b, c);
print_result:
printf("%d %d %d\n", a, b, c);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment