Fw: [問題] __asm寫quicksort的幾個問題
※ [本文轉錄自 C_and_CPP 看板 #1FpSGuSW ]
作者: initial1635 (SurprisingTW) 看板: C_and_CPP
標題: [問題] __asm寫quicksort的幾個問題
時間: Tue Jun 5 16:32:54 2012
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
VC
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
問題(Question):
不穩...有時候能算出答案 有時候無線循環
餵入的資料(Input):
隨機陣列
預期的正確結果(Expected Output):
從小排到大
錯誤結果(Wrong Output):
x=0 q=0 無限循環
程式碼(Code):(請善用置底文網頁, 記得排版)
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <time.h>
using namespace std;
int a[10];
int partition(int* a, int p, int r)
{
int tmp;
int i;
int x;
int q;
r*=4;
__asm
{
mov eax, a
mov ebx, p
mov ecx, r
pushad
partition:
mov edx, [eax+ecx]
mov x, edx //x=a[r]
mov esi, ebx
sub esi, 4 //i=p-1
mov edi, ebx //j=ppfor:
cmp edi, ecx //edi=j=p , ecx =r
jae pforend //if a[j] < x
mov edx, [eax+edi]
cmp edx, x
jae nopif
add esi, 4 // Swap
push edx
mov dl, [eax+esi]
xchg dl, [eax+edi]
mov [eax+esi], dl
pop edx
// End swap nopif:
add edi, 4
jmp pforpforend: // Swap
push edx
add esi, 4
mov dl, [eax+esi]
xchg dl, [eax+ecx]
mov [eax+esi], dl
pop edx
// End swap
shr esi, 2
mov q, esi //edx =i+1
popad
}
cout << "p:" << p << " ";
cout << "r:" << r/4 << " ";
cout << "x:" << x << " ";
cout << "q:" << q << endl;
return q;
}
void quicksort(int a[], int p, int r)
{
int q;
if(p < r) {
q=partition(a, p, r);
quicksort(a, p, q-1);
quicksort(a, q+1, r);
}}
void main()
{
int num=5;
int b=0;
clock_t start_time, end_time;
float total_time =0;
srand(time(NULL));
for(int i=0; i<num; i+=1){
a[i]=(rand()%100)+1;
cout << a[i] << " ";
}
cout << endl;
start_time = clock();
quicksort(a,0,num-1);
//partition(a,0,num-1);
end_time=clock();
for(int i=0; i<num; i+=1){
cout << a[i] << " ";
}
total_time = (float)(end_time-start_time)/CLOCKS_PER_SEC;
cout << endl << "Times:" << total_time << "sec" << endl;
system("pause");
}
補充說明(Supplement):
quicksort的部分寫法就跟C一樣
partition改成用組語來寫
奇怪的是有時候可以列出答案 有時候卻會爆掉
但我只是把partition return的q換成用組語寫而已啊...為什麼會這樣呢?
還有如果quicksort的部分也要用組語寫 要怎麼寫呢?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.44.55.95
推
06/05 17:37, , 1F
06/05 17:37, 1F
→
06/05 18:27, , 2F
06/05 18:27, 2F
※ 發信站: 批踢踢實業坊(ptt.cc)
※ 轉錄者: initial1635 (1.169.186.17), 時間: 06/06/2012 01:11:35
ASM 近期熱門文章
PTT數位生活區 即時熱門文章
3
11