public class binaryheap2 {
/*
* 下沉
*/
public static int[] downAdjust(int arr[],int parent,int length) {
int temp = arr[parent];//临时保证要下沉的元素
int child = 2*parent+1;
while(child<length) {
if(child+1<length && arr[child]>arr[child+1]) {
child++;
}
if(temp<=arr[child]) {
break;
}
arr[parent]=arr[child];
parent = child;
child = 2*parent+1;
}
arr[parent] = temp;
return arr;
}
/*
* 堆排序
*/
public static int[] heapsort(int []arr,int length) {
//构建二叉树
for(int i=(length-2)/2;i>=0;i--) {
arr = downAdjust(arr, i, length);
}
//进行堆排序
for(int i = length-1;i>=1;i--) {
int temp = arr[i];
arr[i]= arr[0];
arr[0]=temp;
arr = downAdjust(arr, 0, i);
}
return arr;
}
public static void main(String []args) {
int []arr = {1,3,5,2,0,10,6};
System.err.println(Arrays.toString(arr));
arr = heapsort(arr,arr.length);
System.err.println(Arrays.toString(arr));
}
}
堆排序(Java)
最新推荐文章于 2021-01-27 15:00:12 发布