2016-04-07 13 views
0
protected void up-heap(int j) { 
while (j > 1) {   // continue until reaching root (or break) 
    int p = parent(j); 
    if (compare(heap.get(j), heap.get(p)) >= 1) break; // heap property verified 
    swap(j, p); 
    j = p;        // continue from the parent's location 
}} 

java.i çalıştı recursive.i dönüştürmek amacıyla nasıl almıyorum kullanarak tekrarlanan içine bu özyinesiz kod yazmak nasıl Birçok web sitesi ama cevap alamadımözyinelemeli fonksiyonu (i özyinelemeli içine bu özyinesiz yöntem yazabilirsiniz nasıl)

+1

Bu soru C++ veya java hakkında mıdır? – user2807083

cevap

2

Nokta, özellike yöntem çağrılarına while döngüsünü yeniden yazmaktır. Bu çok basit:

protected void upHeap(int j) { 
    if (j <= 1) //this handles the condition of the original while loop 
    return; 
    int p = parent(j); 
    if (compare(heap.get(j), heap.get(p)) >= 1) 
    return; // this handles the break from the while loop 
    swap(j, p); 
    upHeap(p); // the recursive method call, replacing j with p 
}