同问新问题,如何不使用递归,改用循环?
afan 发表于 2010-1-24 01:28
算法不是我的,我只在supersp的基础上改为非递归. 没对比,估计效率要比二分优化的递归低.
#Include <Array.au3>
Dim $aArray[35] = [51, 8, 13, 2, 52, 61, 37, 85, 19, 11, 7, 62, 22, 38, 79, 53,54,55,56,57,58,59,60,63,64,90,91,92,93,94,95,96,97,98,99 ]
$begin = TimerInit()
_ArraySort($aArray)
$m = UBound($aArray)
Global $display[1]
;折半法,找出 105/2 的分界线
Local $min=0,$max=$m-1,$mid,$fjx=-1
If $aArray[0]>=58 Then $fjx=0
If $aArray[$max]<58 Then $fjx=$max
While $fjx=-1
$mid=($min+$max)/2
If $aArray[$mid] >= 58 Then
$max=$mid-1
If $aArray[$mid-1] < 58 Then $fjx=$mid
Else
$min=$mid+1
If $aArray[$mid+1] >= 58 Then $fjx=$mid+1
EndIf
WEnd
_xh(0,"",$fjx-1)
For $v2 = $fjx To $m-1
_xh($aArray[$v2],String($aArray[$v2])&"+",$fjx-1)
Next
_ArrayDelete($display, 0)
$dif = TimerDiff($begin)
ConsoleWrite("耗时:"&$dif&',数组个数:'&UBound($display))
;_ArrayDisplay($display,"耗时:"&$dif)
Func _xh($var,$str,$n)
$i_step = 10000
Local $a_temp[$i_step][3], $i_cnt = 1;
$a_temp[0][0] = 1
$a_temp[1][0] = $var
$a_temp[1][1] = $str
$a_temp[1][2] = $n
Local $num, $i, $i_temp
While ($a_temp[0][0] <= $i_cnt)
$i_temp = $a_temp[0][0]
$var = $a_temp[$i_temp][0]
$str = $a_temp[$i_temp][1]
$n = $a_temp[$i_temp][2]
For $i = $n To 0 Step -1
$num = Execute("$var + $aArray[$i]")
Switch $num
Case 105 To 1500
ContinueLoop
Case 102 To 105
_ArrayAdd($display,$str&String($aArray[$i])&"="&String($num))
Case 1 To 102
$i_cnt += 1;根据需要决定是否判断数组超界ReDim
If $i_cnt>=UBound($a_temp,1) Then ReDim $a_temp[UBound($a_temp,1)+$i_step][3]
$a_temp[$i_cnt][0] = $num
$a_temp[$i_cnt][1] = $str&String($aArray[$i]&"+")
$a_temp[$i_cnt][2] = $i-1
EndSwitch
Next
$a_temp[0][0] += 1
WEnd
EndFunc |