我正在尝试使用汇编对字符串数组进行排序。我比较第一个和第二个字母,然后按字母顺序重新排列它们。我几乎已经弄清楚了,但是我的输出重新排列了一些不正确的字符。例如,当打印'eight‘时,它只会打印’eight‘。
.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;
}发布于 2010-10-27 12:06:16
发生的情况是,您正在比较两个字符串的前四个字母,然后使用'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], eaxhttps://stackoverflow.com/questions/4029873
复制相似问题