堆(dui)排序的java实现
public class Heapsort {
private int heap_size;
public static void main(String[] args) {
int[] ints = {1,6,3,9,3,8,3,443};
Heapsort demo = new Heapsort();
int[] arrsort = demo.heapsort(ints);
demo.printarr(arrsort);
int[] arrsort2 = demo.heapsort_des(ints);
demo.printarr(arrsort);
}
public int[] heapsort(int[] arr) {
//堆排序 将堆顶元素交换放到有效值的最后一位 然后再堆化交换后的堆 通过循环直至堆成从小到大排序
buildmaxheap(arr);
for(int i=arr.length-1;i>0;i--){
int temp = arr[0];
arr[0]=arr[i];
arr[i]=temp;
heap_size=heap_size-1;
heapify(arr,0);
}
return arr;
}
public int[] heapsort_des(int[] arr) {
//堆排序 将堆顶元素交换放到有效值的最后一位 然后再堆化交换后的堆 通过循环直至堆成从小到大排序 再逆序数组
buildmaxheap(arr);
for(int i=arr.length-1;i>0;i--){
int temp = arr[0];
arr[0]=arr[i];
arr[i]=temp;
heap_size=heap_size-1;
heapify(arr,0);
}
int temp;
for(int i=0;i<arr.length/2;i++){
temp=arr[i];
arr[i]=arr[(arr.length-i-1)];
arr[(arr.length-i-1)]=temp;
}
return arr;
}
public void printarr(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
System.out.println("");
}
public void buildmaxheap(int[] arr) {
//构建大顶堆
heap_size=arr.length;
for (int i = ((arr.length-1) / 2); i > -1; i--) {
heapify(arr, i);
}
}
public void heapify(int[] arr, int i) {
//堆化arr数组通过递归保证i和其所有子节点都满足最大堆的性质
int l = left(i);
int r = right(i);
int largest = i;
if (l < heap_size && arr[l] > arr[i]) {
largest = l;
}
if (r < heap_size && arr[r] > arr[largest]) {
largest = r;
}
if (largest != i) {
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
heapify(arr, largest);
}
}
public int left(int i) {
return 2 * i;
}
public int right(int i) {
return 2 * i + 1;
}
}