Click to See Complete Forum and Search --> : Quicksort


aznium
April 19th, 2005, 08:03 PM
my first assembly program :D

quicksort . yah!


#include "stdafx.h"
#include "stdio.h"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
int nums = 0;
int *list;

printf("please enter the number of numbers\n");
scanf("%d", &nums);

list = new int[nums];

for(int i = 0; i < nums; i++)
{
printf("please enter number %d\n", i);
scanf("%d", &list[i]);
}

_asm
{
start:
xor eax, eax ; a = 0
mov ebx, nums ; b = nums
call sort ; sort
ret ; return

sort:
cmp ebx, eax ; compare a, b
jge valid ; if b > a, goto valid
ret ; return

valid:
call pivot ; goto pivot
push ebx ; store b into stack
push eax ; store a into stack
inc eax ; a++
call mainloop ; goto mainloop
pop ecx ; retrieve original a from stack
dec eax ; a--
mov edx, list[eax] ; d = nums[a]
push edx ; store d into stack
mov edx, list[ecx] ; d = nums[original a]
mov list[eax], edx ; nums[a] = d
pop edx ; retrieve d from stack
mov list[ecx], edx ; nums[original a] = d
push ebx ; store b into stack
mov ebx, eax ; b = a
mov eax, ecx ; a = original a
call sort ; recursion
pop eax ; retrieve b from stack
pop ebx ; retrieve original b from stack
call sort ; recursion
ret ; return

pivot:
mov ecx, list[eax] ; pivot = nums[a]
ret ; return

mainloop:
cmp eax, ebx ; compare a, b
jl compare ; if a < b goto compare
jl mainloop ; if a < b, loop
ret ; return

compare:
cmp list[eax], ecx ; compare a, pivot
jle lessequal ; a <= e
jg greater ; a > e
ret ; return

lessequal:
inc eax ; a++
ret ; return

greater:
dec ebx ; b--
call swapnums ; goto swapnums
ret ; return

swapnums:
mov edx, list[eax] ; d = a
push edx ; store d into stack
mov edx, list[ebx] ; d = b
mov list[eax], edx ; a = d
pop edx ; retrieve d from stack
mov list[ebx], edx ; b = d
ret ; return
}

for(int i = 0; i < nums; i++)
{
printf("%d", list[i]);
}

scanf("%s");

delete [] list;

return 0;
}




...sniff...and it doesnt work :'( ... im stumped

it doesnt even get to output anything...the program just quits...

i think my problem is with the jumps...the jg, jle...etc
i think it doesnt return to the method that called it?

also on a side note,
why cant i do something like this?

mov list[0], list[1] //where list[0] and list [1] are defined in C++


thx if u can help me :D

Hobson
April 20th, 2005, 05:09 AM
Gratz on your first assembly program!

also on a side note, why cant i do something like this? mov list[0], list[1] //where list[0] and list [1] are defined in C++

That is because you are not allowed to move between two memory locations. At least one argument of mov should be reg or immed.

Also, try debugging your code. You may use TurboDebugger (td.exe), shipped with Borland C++ 3.1 or Tasm/Tlink, or MSVC, or some disassembler, like WDasm32.