Copy Code code as follows:
Import Java.util.Arrays;
public class Heapsort {
public static void Heapsort (datawraper[] data) {
System.out.println ("start sort");
int arraylength=data.length;
Loop Build Heap
for (int i=0;i<arraylength-1;i++) {
Build a heap
Buildmaxheap (data,arraylength-1-i);
Swap heap top and last element
Swap (data,0,arraylength-1-i);
System.out.println (arrays.tostring (data));
}
}
private static void Swap (datawraper[] data, int i, int j) {
TODO auto-generated Method Stub
Datawraper Tmp=data[i];
DATA[I]=DATA[J];
data[j]=tmp;
}
Build a stack of data arrays from 0 to lastindex
private static void Buildmaxheap (datawraper[] data, int lastindex) {
TODO auto-generated Method Stub
Starting from the parent node of the node (last node) at lastindex
for (int i= (lastIndex-1)/2;i>=0;i--) {
K Save the node being judged
int k=i;
If the child node of the current K node exists
while (K*2+1<=lastindex) {
The index of the left child node of the K node
int biggerindex=2*k+1;
If Biggerindex is less than lastindex, that is, the right child node of the K node represented by biggerindex+1 exists
if (Biggerindex<lastindex) {
If the value of the right child node is greater
if (Data[biggerindex].compareto (data[biggerindex+1]) <0) {
Biggerindex always record the index of a larger child node
biggerindex++;
}
}
If the value of the K node is less than the value of its larger child node
if (Data[k].compareto (Data[biggerindex]) <0) {
Exchange them
Swap (Data,k,biggerindex);
Assign Biggerindex to K, start the next loop in the while loop, and reassure the K node that the value is greater than its left and right child nodes
K=biggerindex;
}else{
Break
}
}
}
}
public static void Main (string[] args) {
TODO auto-generated Method Stub
Datawraper [] data={
New Datawraper (21, ""),
New Datawraper (30, ""),
New Datawraper (49, ""),
New Datawraper (30, "*"),
New Datawraper (16, ""),
New Datawraper (9, ""),
};
System.out.println ("Before: \ n" +arrays.tostring (data));
Heapsort (data);
System.out.println ("after sort: \ n" +arrays.tostring (data));
}
}
Results:
Before sorting:
[21, 30, 49, 30*, 16, 9]
Start sorting
[9, 30, 21, 30*, 16, 49]
[16, 30*, 21, 9, 30, 49]
[9, 16, 21, 30*, 30, 49]
[9, 16, 21, 30*, 30, 49]
[9, 16, 21, 30*, 30, 49]
After sorting:
[9, 16, 21, 30*, 30, 49]