|
import java.awt.*; import java.applet.Applet;
public class New extends Applet { static int c; static Button b1; static Label l; static TextField t,t2; static List list;
public void init() {
b1 = new Button("DeHeap");
l = new Label("Enter Score"); t = new TextField(10); t2 = new TextField(10); list = new List(10);
add(b1);
add(l); add(t); add(list); add(t2);
}
public boolean action (Event e,Object o) { if (e.target==t) // entered return in textbox.. add to heap { list.addItem(t.getText()); if (list.getItemCount()>1) // if more than one thing on heap { boolean done = false; int val = list.getItemCount();
while (!done ) { if (Integer.parseInt(list.getItem(val-1)) > Integer.parseInt(list.getItem(val/2-1))) { String temp = list.getItem(val-1); // -1 because listbox uses 0 position list.replaceItem(list.getItem(val/2-1),val-1); // replace child with parent list.replaceItem(temp,val/2-1); replace child val = val/2; // move to this node’s parent } else done = true; // no more to go up or at root if (val < 2 ) done = true; } }
t.setText(""); }
if (e.target==b1) { t2.setText(list.getItem(0)); list.replaceItem(list.getItem(list.getItemCount()-1),0); list.remove(list.getItemCount()-1); boolean exit = false; int bigChild=0; int val = 1; String leftChild =list.getItem(val*2-1); String rightChild = list.getItem(val*2); if (Integer.parseInt(leftChild) > Integer.parseInt(rightChild)) bigChild = Integer.parseInt(leftChild); else bigChild = Integer.parseInt(rightChild); while (!exit) { if (bigChild > Integer.parseInt(list.getItem(val-1))) { if (bigChild == Integer.parseInt(leftChild)) { String temp = list.getItem(val-1); list.replaceItem(list.getItem(val*2-1),val-1); list.replaceItem(temp,val*2-1); } else { String temp = list.getItem(val-1); list.replaceItem(list.getItem(val*2),val-1); list.replaceItem(temp,val*2); } val = val*2; } else exit = true; if (val*2 <= list.getItemCount()) { leftChild =list.getItem(val*2-1); if (val*2 != list.getItemCount()) rightChild = list.getItem(val*2); else rightChild = "0"; if (Integer.parseInt(leftChild) > Integer.parseInt(rightChild)) bigChild = Integer.parseInt(leftChild); else bigChild = Integer.parseInt(rightChild); } else exit = true; } }
return true; }
}
|