package cn.bintree;
import java.util.Arrays;
/*
* create by yike on 2020/10/18
* 堆排序
*/
public class HeapSortDemo {
public static void main(String[] args) {
int[] arry = {5,6,2,3,9,7,1};
HeapSort heap = new HeapSort();
heap.setHeap(arry);
System.out.println(Arrays.toString(heap.ascOrder()));
int[] arry1 = {8,4,6,32,54,2,51};
heap.setHeap(arry1);
System.out.println(Arrays.toString(heap.desOrder()));
}
}
class HeapSort{
/**
* @len 记录每次循环后,下次数组长度
* @heap 接受堆排序的数组
* @temp 用于交换元素位置时的辅助指针
*/
private int len;
private int[] heap;
private int temp;
public void setHeap(int[] heap) {
this.heap=heap;
this.len=heap.length;
}
public int[] ascOrder() {//大顶推完成数组升序排序
while(len>=2) {
//第一轮
for(int i=(len/2-1);i>=0 && i<len;i--) {
ascNode(i);
}
heap[0]=heap[len-1];
heap[len-1]=temp;
len--;
}
return heap;
}
public void ascNode(int n) {//非页子节点的比较和交换过程
temp=heap[n];
if((2*n+1)<len && temp<heap[2*n+1]) {
heap[n]=heap[2*n+1];
heap[2*n+1]=temp;
temp=heap[n];
}
if((2*n+2)<len && temp<heap[2*n+2]) {
heap[n]=heap[2*n+2];
heap[2*n+2]=temp;
temp=heap[n];
}
}
public int[] desOrder() {//小顶堆完成数组降序排序
while(len>=2) {
for(int i=(len/2-1);i>=0 && i<len;i--) {
desNode(i);
}
heap[0]=heap[len-1];
heap[len-1]=temp;
len--;
}
return heap;
}
public void desNode(int n) {
temp=heap[n];
if((2*n+1)<len && temp>heap[2*n+1]) {
heap[n]=heap[2*n+1];
heap[2*n+1]=temp;
temp=heap[n];
}
if((2*n+2)<len && temp>heap[2*n+2]) {
heap[n]=heap[2*n+2];
heap[2*n+2]=temp;
temp=heap[n];
}
}
}
用java语言实现升序/降序排序(堆排序)
最新推荐文章于 2024-05-28 21:49:48 发布