堆排序:
首先要满足:是一颗近似完全二叉树
大顶堆是父节点的值不小于子节点
小顶堆是父节点的值不大于子节点
大顶堆代码示例:
package sort;
import java.util.Arrays;
public class HeapSort {
public static void main(String[] args) {
int a [] = {4,1,6,3,5,67,6788,1,8788,5};
heapsort(a);
System.out.println(Arrays.toString(a));
}
public static void heapsort(int[] a) {
int n = a.length;
for (int i = (n-2)/2; i >=0; i--) {
downAdjust(a,i,n);
}
for (int i = n-1; i >=0 ; i--) {
int temp = a[i];
a[i] = a[0];
a[0] = temp;
downAdjust(a,0,i);
}
}
private static void downAdjust(int[] a, int i, int n) {
int temp = a[i];
int child = 2*i+1;
while (child<n){
if(child+1<n&&a[child+1]>a[child]){
child++;
}
if(temp>=a[child]){
break;
}
a[i] = a[child];
i = child;
child = 2*child+1;
}
a[i] = temp;
}
}
小顶堆代码示例:
package sort;
import java.util.Arrays;
public class HeapSort2 {
public static void main(String[] args) {
int a [] = {4,1,6,3,5,67,6788,1,8788,5};
heapsort(a);
System.out.println(Arrays.toString(a));
}
public static void heapsort(int[] a) {
int n = a.length;
for (int i = (n-2)/2; i >=0; i--) {
downAdjust(a,i,n);
}
for (int i = n-1; i >=0 ; i--) {
int temp = a[i];
a[i] = a[0];
a[0] = temp;
downAdjust(a,0,i);
}
}
private static void downAdjust(int[] a, int i, int n) {
int temp = a[i];
int child = 2*i+1;
while (child<n){
if(child+1<n&&a[child+1]<a[child]){
child++;
}
if(temp<=a[child]){
break;
}
a[i] = a[child];
i = child;
child = 2*child+1;
}
a[i] = temp;
}
}