-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathgnome-sort.asm
75 lines (58 loc) · 1.61 KB
/
gnome-sort.asm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
.386
.model flat, c
.code
;Code by Miguel Casillas.
;This code can be used and reproduced, please give credit
;void GnomeSort(void *pArray, int nItems);
GnomeSort PROC
;These registers must be restored at the end
push EBP
mov EBP, ESP
push EBX
push ESI
push EDI
;EBP + 8 is the array
;EBP + 12 is the number of items in the array
mov ESI, [EBP+8] ;ESI is the array
mov ECX, [EBP+12] ;setting ECX to the number of items
xor EAX, EAX ;Setting EAX to 0, it'll be our iterator
MainLoop:
;If 'i' >= the number of items, exit the loop
cmp EAX, ECX
jge EndLoop
;If 'i' == 0, move to the next element
cmp EAX, 0
je IncreaseCounter
;If array[i-1] <= array[i], it means they are
;sorted, so move to the next element
mov EBX, [ESI] ;EBX = array[i]
mov EDX, [ESI-4] ;EDX = array[i-1]
cmp EDX, EBX
jle IncreaseCounter
;else, swap array[i-1] with array[i]
push [ESI]
push [ESI-4]
pop [ESI]
pop [ESI-4]
;Move to the previous element in the array
;and decrease 'i'
sub ESI, 4
dec EAX
;Loop back to the top
BackToMainLoop:
jmp MainLoop
;Moving to the next element in the array
;and increasing 'i'
IncreaseCounter:
inc EAX
add ESI, 4
jmp BackToMainLoop
EndLoop:
;Restoring the registers
pop EDI
pop ESI
pop EBX
pop EBP
RET
GnomeSort ENDP
END