Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 英特尔8086插入排序:跳过阵列中的数字_Arrays_Assembly_Intel_X86 16_Insertion Sort - Fatal编程技术网

Arrays 英特尔8086插入排序:跳过阵列中的数字

Arrays 英特尔8086插入排序:跳过阵列中的数字,arrays,assembly,intel,x86-16,insertion-sort,Arrays,Assembly,Intel,X86 16,Insertion Sort,所以我们目前正在研究教授给我们看的英特尔8086插入排序代码。他想让我们弄清楚为什么代码会从他从web上获取的代码中跳过数组中的第0个元素和数组中的第3个元素 ; void isort(int *a, int n) ; sorts the first n elements of a ; ; Parameters ; a - pointer to the array ; n - number of elements to sorts %define a [ebp + 8] %defi

所以我们目前正在研究教授给我们看的英特尔8086插入排序代码。他想让我们弄清楚为什么代码会从他从web上获取的代码中跳过数组中的第0个元素和数组中的第3个元素

; void isort(int *a, int n)
;   sorts the first n elements of a
;
; Parameters
;   a - pointer to the array
;   n - number of elements to sorts

%define a [ebp + 8]
%define n [ebp + 12]
isort:
  enter 0, 0
  pusha

  mov ecx, 1
  for:
    mov ebx, ecx
    imul ebx, 4
    add ebx, a
    mov ebx, [ebx]

    mov edx, ecx
    dec edx

    while:
      cmp edx, 0
      jl while_quit

      mov eax, edx
      imul eax, 4
      add eax, a

      cmp ebx, [eax]
      jge while_quit

      mov esi, [eax]

      mov dword [eax + 4], esi

      dec edx
      jmp while
    while_quit:

    mov [eax], ebx

    inc ecx
    cmp ecx, n
    jl for

  popa
  leave
  ret

样本数组是{5,8,12,2,1,7}。这更多是为了理解8086语言,因为我们几天前刚刚开始学习,我想知道是否有人能解释一下如何以及可能出现的问题。

考虑一下当
ECX
为1时,代码会做什么:

  • while
    循环将以
    EBX=8
    EDX=0
    输入
  • 退出时将不执行
    jl,因为
    EDX
    为0
  • EBX
    [EAX]
    进行比较。就是,;8与
    a[0]
    比较,后者为5,因此在退出时取
    jge
  • mov[eax],ebx
    a[0]
    存储8,因此您的数组现在包含
    {8,8,12,2,1,7}
    。显然不是你想要的,因为你失去了一个原始元素

除了代码的逻辑缺陷外,那些
imul
指令完全没有必要,因为您可以在x86上使用缩放索引。因此,排序代码可以简化为以下内容(我已验证它对数组进行了正确排序):

mov-ecx,1
有关:
; esi=&a[holePos]
lea esi[a+ecx*4]
; valueToInsert=a[holePos]
mov ebx,[esi]
而:
; 我们到达数组的开头了吗?
cmp esi,偏移量a
在你退出的时候离开
; 输入值
我使用的是MASM语法,但你明白了

mov ecx, 1
for_:
  ; esi = &a[holePos]   
  lea esi,[a + ecx*4]
  ; valueToInsert = a[holePos]
  mov ebx, [esi]

  while_:
    ; Did we reach the beginning of the array?
    cmp esi, OFFSET a
    jle while_quit

    ; valueToInsert < a[holePos-1] ?
    cmp ebx, [esi-4]
    jge while_quit

    ; a[holePos] = a[holePos-1]
    mov eax, [esi-4]
    mov [esi], eax

    ; esi = &a[holePos-1]
    sub esi,4
    jmp while_
  while_quit:

  ; a[holePos] = valueToInsert
  mov [esi], ebx

  inc ecx
  cmp ecx, 6
  jl for_