【问题标题】:Sorting Integers in Assembly在汇编中对整数进行排序
【发布时间】:2015-09-19 09:41:19
【问题描述】:

项目是在汇编中创建一个冒泡排序算法,它将对给定的整数列表进行排序。我已经下降并且我的输出在某种程度上是正确的。似乎在组合数字顺序时会混淆,这就是我的意思:

10 -20 5 12 30 -5 -22 55 52 0

整数个数 = 10 Ascend_or_Descend = 1

0 5 10 12 30 52 55 -22 -20 -5

这是包含用于测试的主要方法的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <io.h>

int sorter (int* list, int count, int opcode)
{
__asm
{
mov eax, 0          ; zero out the result
mov ebx, opcode     ; move opcode to ebx for comparison

mov ecx, count; //OuterLoop counter
cmp ecx, 1; //check length  
jle Return;  

OuterLoop:
   mov edi, list; //move in list    
   push ecx; 

   mov ecx, count; 
   dec ecx; //Decrement inner loop
InnerLoop:
   mov eax, [edi]; //First Value in list
   cmp ebx, 1; 
   je  Ascending; 
   cmp eax, [edi+4]; //next int is 4 bits away
   jb  Swap; 
   jmp Continue; 
Ascending:
   cmp eax, [edi+4]; //Again compare with next int
   ja  Swap; //if no swap
   jmp Continue; 
Swap:
   mov edx, [edi+4]; //Move to temp register
   mov [edi+4], eax; //Move stored value there
   mov [edi], edx; //Return temp value to list
Continue:
   add edi, 4; //Increment to move to next int
   loop InnerLoop; 
   pop ecx; //reset counter
   loop OuterLoop; 
Return:; 
}

}


int main(int argc, char** argv)
{
int numlist[1000], asc;
FILE *fptr;

int i = 0;

if (argc != 3)
{
    printf("Usage: %s filename asc_des\n", argv[0]);
    return 1;
}

asc = atoi (argv[2]);
asc = (asc == 1) ? 1 : 2;

printf("\n");

fptr = fopen((argv[1]), "rtc");
if (fptr == NULL)
  printf( "File %s was not opened\n",argv[1] );
else
{
  /* Set pointer to beginning of file: */
  fseek( fptr, 0L, SEEK_SET );

  /* Read data from file: */
  while ( fscanf(fptr, "%d", &numlist[i]) != EOF )
  {
      printf( "%d ", numlist[i] );
      i++;
  }

  printf( "\n\nNumber of integer = %d\n", i );
  printf( "Ascend_or_Descend = %d\n\n", asc );
  fclose( fptr );
  }

  sorter( numlist, i, asc);

  for (int j = 0; j < i; j++)
      printf( "%d ", numlist[j] );

  printf("\n");

  return 0;
  }

【问题讨论】:

    标签: sorting assembly bubble-sort


    【解决方案1】:

    来自英特尔的手册:

    术语“上面”和“下面”与CF 标志相关联,指的是两个无符号之间的关系 整数值。术语“更大”和“更少”与SFOF 标志相关联,指的是关系 在两个有符号整数值之间

    通过使用jbja,您将比较结果视为无符号比较的结果,因此带符号的数字最终会出现在排序数组的末尾(例如 -22 解释为一个无符号的 32 位值是 4294967274)。

    您应该使用jl 代替jb,并使用jg 代替ja

    【讨论】:

    • 抱歉,回复晚了,但您是正确的。对这些东西不熟悉,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多