In: Biology
Use the Heap class provided to implement a sort routine in a Main class where the user enters a series of values, each value is then pushed onto a heap, then the values are printed out in ascending order.
public class Heap {
public static final int SIZE = 1025;
public Heap() {
elt = new Element[SIZE];
lastLoc = 0;
}
public void push(String k, Object o) {
if (!fullCheck()) {
lastLoc++;
elt[lastLoc] = new Element(k,o);
int loc = lastLoc;
while (loc > 1 && elt[loc].key.compareTo(elt[loc/2].key) < 0) {
Element hold = elt[loc];
elt[loc] = elt[loc/2];
elt[loc/2] = hold;
loc = loc/2;
}
}
}
public void pop() {
if (!emptyCheck()) {
elt[1] = elt[lastLoc];
lastLoc--;
int loc = 1;
while (2*loc <= lastLoc) {
loc = 2*loc;
if (loc < lastLoc && elt[loc +1].key.compareTo(elt[loc].key) < 0) loc=loc+1;
if (elt[loc].key.compareTo(elt[loc/2].key) < 0) {
Element hold = elt[loc/2];
elt[loc/2] = elt[loc];
elt[loc] = hold;
}
}
}
}
public Object top() {
return elt[1].payload;
}
public Object topKey() {
return elt[1].key;
}
public boolean emptyCheck() {
return (lastLoc == 0);
}
public boolean fullCheck() {
return (lastLoc == SIZE-1);
}
private Element[] elt;
private int lastLoc;
}
public class Element {
public Element(String s) {
key = s;
payload = null;
}
public Element(String s, Object obj) {
key = s;
payload = obj;
}
public String key;
public Object payload;
}
*******hope it will help you*************
import java.util.*;
class SortStack
{
public static Stack<Integer>
sortstack(Stack<Integer>
input)
{
Stack<Integer> tmpStack = new
Stack<Integer>();
while(!input.isEmpty())
{
int tmp =
input.pop();
while(!tmpStack.isEmpty() && tmpStack.peek()
<
tmp)
{
input.push(tmpStack.pop());
}
tmpStack.push(tmp);
}
return tmpStack;
}
public static void main(String args[])
{
Stack<Integer> input = new
Stack<Integer>();
input.add(34);
input.add(3);
input.add(31);
input.add(98);
input.add(92);
input.add(23);
Stack<Integer>
tmpStack=sortstack(input);
System.out.println("Sorted numbers
are:");
while (!tmpStack.empty())
{
System.out.print(tmpStack.pop()+" ");
}
}
}