Psst.. new poll here.
Psst.. new forums here.
Microsoft is blocking us again (TY IP Reputation!) so just use oauth login instead. :)
Paste
Pasted as Java by registered user SKYDOS ( 17 years ago )
import java.io.*;
public class Main {
static int[] heap;
public static void BuildHeap(int size) {
int from = size, root, tmp, current;
for (int pos=1; pos<=from; pos++) {
current=pos;
root=pos/2;
while (root>0 && heap[root]<heap[current]) {
tmp=heap[root];
heap[root]=heap[current];
heap[current]=tmp;
current=root;
root=current/2;
}
}
}
public static void MoveDown (int size) {
int root, left, right, tmp;
for (int pos=1;;) {
root = pos;
left=pos*2; right=left+1;
if (left<=size && right<=size) {
if (heap[left]>=heap[right] && heap[left]>heap[root]) {
tmp = heap[left];
heap[left] = heap[root];
heap[root] = tmp;
pos=left;
continue;
}
if (heap[right]>=heap[left] && heap[right]>heap[root]) {
tmp = heap[right];
heap[right] = heap[root];
heap[root] = tmp;
pos=right;
continue;
}
break;
} else {
if (left<=size && right>size && heap[left]>heap[root]) {
tmp = heap[left];
heap[left] = heap[root];
heap[root] = tmp;
pos=left;
} else break;
}
}
}
public static void main (String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer (new BufferedReader(new InputStreamReader (System.in, "ISO-8859-1")));
PrintWriter out = new PrintWriter (new OutputStreamWriter (System.out, "ISO-8859-1"));
in.nextToken(); int n=(int)in.nval;
heap=new int[n+1];
int tmp, back=n;
for (int i=1; i<=n; i++) {
in.nextToken(); heap[i]=(int)in.nval;
}
BuildHeap(n);
for (;n>0;) {
tmp=heap[1];
heap[1]=heap[n];
heap[n]=tmp;
n--;
MoveDown (n);
}
for (int i=1; i<=back; i++) out.print (heap[i]+" ");
out.close();
}
}
Revise this Paste