我從算法書的介紹中編寫了MAX-HEAPIFY(A,i)方法。現在我想用while循環不遞歸地編寫它。你能幫我嗎?如何在不遞歸的情況下編寫Max Heap代碼
2
A
回答
2
你可以使用while循環條件你的我< = HEAPSIZE和使用所有其他相同的條件,除非你找到正確的位置只是打破循環。 代碼: -
while (i < = heapsize) {
le <- left(i)
ri <- right(i)
if (le<=heapsize) and (A[le]>A[i])
largest <- le
else
largest <- i
if (ri<=heapsize) and (A[ri]>A[largest])
largest <- ri
if (largest != i)
{
exchange A[i] <-> A[largest]
i <- largest
}
else
break
}
0
上述工程的解決方案,但我認爲下面的代碼是接近遞歸版本
(* Code TP compatible *)
const maxDim = 1000;
type TElem = integer;
TArray = array[1..maxDim]of TElem
procedure heapify(var A:TArray;i,heapsize:integer);
var l,r,largest,save:integer;
temp:TElem;
(*i - index of node that violates heap property
l - index of left child of node with index i
r - index of right child of node with index i
largest - index of largest element of the triplet (i,l,r)
save - auxiliary variable to save the value of i
temp - auxiliary variable used for swapping *)
begin
repeat
l:=2*i;
r:=2*i + 1;
if(l <= heapsize) and (A[l] > A[i]) then
largest:=l
else
largest:=i;
if(r <= heapsize) and (A[r] > A[largest]) then
largest:=r;
(*Now we save the value i to check properly the termination
condition of repeat until loop
The value of i will be modified soon in the if statement *)
save:=i;
if largest <> i then
begin
temp:=A[i];
A[i]:=A[largest];
A[largest]:=temp;
i:=largest;
end;
until largest = save;
(*Why i used repeat until istead of while ?
because body of the called procedure will be executed
at least once *)
end;
還有一件事,在Wirth的算法+數據結構=程序
可找到沒有遞歸的篩選程序
但我們應該引入布爾變量或break來消除goto語句
相關問題
- 1. 如何在不遞歸的情況下編寫這個VBA程序
- 2. 如何在不調用多次輸入的情況下編寫遞歸函數?
- 3. 如何遞歸編寫代碼?
- 4. 這個函數如何在不遞歸的情況下實現?
- 5. 如何在不改變變量的情況下進行遞歸
- 6. 在不使用遞歸的情況下迭代父節點PHP
- 7. 如何在不使用全局變量的情況下編寫此代碼?
- 8. 如何在不使用PEAR :: DB的情況下重新編寫此代碼?
- 9. as3 |如何在不使用函數的情況下編寫onComplete代碼
- 10. 是否可以在不使用遞歸的情況下編寫JSON解析器?
- 11. 如何編寫迭代版本的遞歸方案代碼
- 12. 如何在不使用GUI的情況下編寫Jmeter腳本?
- 13. 如何在不使用union的情況下編寫Sql語句?
- 14. 如何在不下載源代碼的情況下使用EXSLT?
- 15. 如何在不使用撇號的情況下編寫此JavaScript
- 16. 如何在不溢出堆棧的情況下在JavaScript中編寫遞歸阻塞函數?
- 17. 在不使用python對象的情況下重寫代碼
- 18. SAS:如何在不返回結果的情況下編寫Teradata查詢傳遞?
- 19. 需要幫助編寫一般情況下的僞代碼
- 20. 如何在不顯示ASCII碼的情況下在java中編寫Unicode?
- 21. 如何在不添加不可達代碼的情況下編譯異步lambda?
- 22. 如何編寫僞代碼的遞歸關係?
- 23. Scala代碼在不使用scalac編譯的情況下運行?
- 24. 如何在不重寫的情況下重新執行代碼部分?
- 25. 如何在不使用遞歸的情況下故意觸發StackOverflowException?
- 26. 如何在不更改源代碼的情況下禁用TLSv1?
- 27. 如何在不顯示代碼的情況下調用js
- 28. Python中的遞歸和異常,如何在不丟失遞歸堆棧的情況下捕獲異常
- 29. 如何在不訪問鏈接的情況下遞歸訪問鏈接?
- 30. 你會如何遞歸編寫這段代碼?
發佈您的遞歸版本。 – 2014-10-10 07:53:37