[英]Insertion sort in assembler doesn't work
I have to do insertion sort of numbers in NASM.我必须在 NASM 中插入数字。 I have a file which generates random numbers and generate output file with numbers in binary form.我有一个文件,它生成随机数并生成带有二进制格式数字的输出文件。 My program loads this as input file and should give output with numbers sorted using insertion sort, also in binary form.我的程序将其加载为输入文件,并应给出使用插入排序排序的数字的输出,也是二进制形式。
My code:我的代码:
; Template assembler source file
section .text
global _start
_start:
; put your code here
mov eax, 3
mov ebx, 0
mov ecx, array
mov edx, 4*32768
int 80h
mov [fileLength], eax
shr eax,2
dec eax
mov [number], eax
mov ebx, 1
outerloop:
mov ecx,[array + 4*ebx]
mov [item],ecx
mov ecx,ebx
interloop:
mov edx,ecx
dec edx
mov esi, [array + 4*edx]
cmp esi,[array + 4*ecx]
jb koniec
mov eax,[array + 4*edx]
mov [array + 4*ecx],eax
loop interloop
koniec:
mov edx,[item]
mov [array + 4*ecx],edx
inc ebx
cmp ebx,[number]
jne outerloop
mov eax, 4
mov ebx, 1
mov ecx, array
mov edx, [fileLength]
int 80h
; exit to linux
mov eax,1
mov ebx,0
int 80h
; initialized data section
; use directives DB (byte), DW (word), DD (doubleword), DQ (quadword)
section .data
; uninitialized data section
; use directives RESB (byte), RESW (word), RESD (doubleword), RESQ (quadword)
section .bss
fileLength resd 1
number resd 1
array resd 32768
item resd 1
Pseudo code that I used to write insertion sort:我用来写插入排序的伪代码:
for i ← 1 to i ← length(A)-1
{
// A[ i ] is added in the sorted sequence A[0, .. i-1]
// save A[i] to make a hole at index iHole
item ← A[i]
iHole ← i
// keep moving the hole to next smaller index until A[iHole - 1] is <= item
while iHole > 0 and A[iHole - 1] > item
{
// move hole to next smaller index
A[iHole] ← A[iHole - 1]
iHole ← iHole - 1
}
// put item in the hole
A[iHole] ← item
}
source: http://en.wikipedia.org/wiki/Insertion_sort来源: http : //en.wikipedia.org/wiki/Insertion_sort
My knowledge about it is pretty small and I don't know what goes wrong.我对它的了解非常少,我不知道出了什么问题。 It sometimes sorts first few numbers but the rest of them is not sorted correctly.它有时对前几个数字进行排序,但其余数字排序不正确。
You have to change the line你必须改变线路
cmp esi, [array + 4*edx]
to到
cmp esi, [item]
and remove dec eax
before your outerloop
.并在您的外outerloop
之前删除dec eax
。 It should work.它应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.