Import Java.util.Arrays;
Public class Heapsort {
The array arr subscript 0 is not used, the number to be sorted is placed in the position labeled 1 ~ arr.length-1, and the elements on these positions are sorted
Public static void sort (int arr[]) {
Heapsort hs = new Heapsort ();
hs.buildmaxheap (arr, 1, arr.length-1);
System. out.println ("buildmaxheap result:" + arrays.tostring (arr));
hs.adjustheap (arr, 1, arr.length-1);
}
Build Maximum Heap
public void Buildmaxheap (int[] arr, int start, int end) {
For (int i = end; i >= start; i--) {
Downwithcycle (arr, I, end);
}
}
Heap Adjustment
public void Adjustheap (int[] arr, int start, int end) {
For (int i = end; i > start; i--) {
Swap (arr, start, i);
System. out.println ("swap result:" + arrays.tostring (arr));
Downwithcycle (arr, start, i-1);
}
}
Down filter
public void Downwithcycle (int[] arr, int start, int end) {
if (start >= end) {
return;
}
int index = start;
int leftindex = 2 * index;
int rightindex = 2 * index + 1;
While (leftindex <= end) {
int biggestindex = index;
if(arr[leftindex]>arr[Biggestindex]) {
Biggestindex = Leftindex;
}
if (rightindex <= end) && (arr[Rightindex] > Arr[biggestindex]){
Biggestindex = Rightindex;
}
if (biggestindex! = index) {
Swap (arr,index,biggestindex);
index = biggestindex;
Leftindex = 2 * index;
Rightindex = 2 * index + 1;
}else{
return;
}
}
}
Swap the elements labeled A and B
private void swap (int[] arr, int A, int b) {
int temp = arr[a];
arr[A] = arr[b];
arr[b] = temp;
}
public static void Main (string[] args) {
int[] arr = {0, one, 2, +, 444, 8 ,, +);
System. out.println ("Origin:" + arrays.tostring (arr));
Heapsort.sort (arr);
System. out.println ("Result:" + arrays.tostring (arr));
}
}
Heap sort (max heap)