views:

75

answers:

1

I'm trying to figure out sorting an array of strings using assembly. I compare the first and the second alphabets and then rearrange them in alphabethic order. I have it almost figured out but my output is rearranging some character incorrectly. For example, when printing 'eight', it'll just print '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;
 }
+1  A: 

What's happening is that you are comparing the first letters of two strings, then using the 'xchg' instruction to exchange first four letters of each string.

If it's okay for you that they will not be fully sorted (just reordered in the order of nondecreasing first letters), you can duplicate the xchg fragment five times to complete the exchange.

Also, I'm not sure about your loops, and whether they are executed the correct number of times. As a general point, try not to use the 'loop' instruction, use explicit conditional jumps such as jnz, they are faster.

edit:

 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
Did you mean instead of using [esi + 20], use [esi +4] then +8, +12, +16, +20... could you show an example of what you said
justbrianr