【问题标题】:Bubble Sort in Assembly装配中的冒泡排序
【发布时间】:2010-10-27 04:01:54
【问题描述】:

我正在尝试使用汇编对字符串数组进行排序。我比较了第一个和第二个字母,然后按字母顺序重新排列它们。我几乎想通了,但是我的输出错误地重新排列了某些字符。例如,当打印 '8' 时,它只会打印 'eigh'。

.386
public _Sort
.model flat
.code
_Sort proc
 push ebp
 mov ebp, esp
 push esi
 push edi
 mov ecx, 10
 mov eax, 1
 dec ecx

L1:
 push ecx
 mov esi, [ebp+8]  

L2:
 mov al, [esi]
 cmp [esi + 20], al
 jg L3
 mov eax, [esi]
 xchg eax, [esi + 20]
 mov [esi], eax

L3: 
add esi, 20
loop L2
pop ecx
loop L1
L4:
pop edi
pop esi
pop ebp 

ret
_Sort endp
end
#include <iostream>
using namespace std;
extern "C" int Sort (char [] [20], int, int);
void main ()
              { 
         char Strings [10] [20]  = { "One",

                                     "Two",

                                     "Three",

                                     "Four",

                                     "Five",

                                     "Six",

                                     "Seven",

                                     "Eight",

                                     "Nine",

                                      "Ten" };
 int i;
 cout << "Unsorted Strings are" << endl;
 for (i = 0; i < 10; i++)
  cout << '\t' << Strings [i] << endl;
 Sort (Strings, 10, 20);
 cout << "Sorted Strings are" << endl;
 for (i = 0; i < 10; i++)
  cout << '\t' << Strings [i] << endl;
 }

【问题讨论】:

  • 如果它让你考虑更好的算法,那你很幸运,它不起作用。

标签: sorting assembly bubble-sort


【解决方案1】:

您正在比较两个字符串的前四个字母,然后使用“xchg”指令交换每个字符串的前四个字母。

如果您认为它们不会被完全排序(只是按照首字母不递减的顺序重新排序),您可以将 xchg 片段复制五次以完成交换。

另外,我不确定您的循环,以及它们是否执行了正确的次数。一般来说,尽量不要使用'loop'指令,使用显式条件跳转,比如jnz,它们会更快。

编辑:

 mov eax, [esi] 
 xchg eax, [esi+20] 
 mov [esi], eax

 mov eax, [esi+4] 
 xchg eax, [esi+24] 
 mov [esi+4], eax

 mov eax, [esi+8] 
 xchg eax, [esi+28] 
 mov [esi+8], eax

 mov eax, [esi+12] 
 xchg eax, [esi+32] 
 mov [esi+12], eax

 mov eax, [esi+16] 
 xchg eax, [esi+36] 
 mov [esi+16], eax

【讨论】:

  • 你的意思是不是使用 [esi + 20],而是使用 [esi +4] 然后 +8、+12、+16、+20... 你能举个例子来说明你所说的吗
猜你喜欢
  • 1970-01-01
  • 2012-07-14
  • 1970-01-01
  • 1970-01-01
  • 2013-10-09
  • 2017-03-11
  • 2015-09-12
  • 2014-02-25
相关资源
最近更新 更多