package ugly;
public class heapSort {
//调整
public static void heapAdjust(int[] array , int index, int end){
int lchild = 2*index;
int rchild = 2*index+1;
int max = index;
if (index <= end/2){
if(lchild <= end && array[lchild] > array[max]) max = lchild;
if(rchild <= end && array[rchild] > array[max]) max = rchild;
if (max != index){
int tmp = array[max];
array[max]= array[index];
array[index] = tmp;
//避免调整之后以max为父节点的子树仍然不是堆
heapAdjust(array, max, end);
}
}
}
//建立堆
public static void buildHeap(int[] array ,int end){
//非叶节点最大序号值为end/2
for(int i = end/2; i >= 1; i--){
heapAdjust(array,i,end);
}
}
//堆排序
public static void HeapSort(int[] array ,int end){
buildHeap(array ,end);
for(int i = end; i >=1; i--){
//交换
int tmp = array[i];
array[i]= array[1];
array[1] = tmp;
//将1至i-1中最大值调整到i-1位置
heapAdjust(array,1,i-1);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] test= {-1,15,100,200,153,21,73,85,2,46,1};
HeapSort(test,10);
for (int k : test){
System.out.print(k+" ");
}
}
}
没有合适的资源?快使用搜索试试~ 我知道了~
堆排序堆排序C语言和java语言
资源推荐
资源详情
资源评论
收起资源包目录
堆排序C语言和java语言.zip (2个子文件)
heapSort.java 1KB
堆排序.cpp 1KB
共 2 条
- 1
资源评论
瞬间的醒悟
- 粉丝: 448
- 资源: 104
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功