堆排序
来源:互联网 发布:淘宝a店是什么店 编辑:程序博客网 时间:2024/05/19 07:11
public class Heapsort {
//找到左孩子
private static int leftChild(int i){
return 2*i+1;
}
private static <AnyType extends Comparable<? super AnyType>>
void percDown(AnyType[] a ,int i,int n){
int child;
AnyType tmp;
for(tmp=a[i];leftChild(i)<n;i=child){
child=leftChild(i);
if(child!=n-1&&a[child].compareTo(a[child+1])<0)
child++;
if(tmp.compareTo(a[child])<0)
a[i]=a[child];
else
break;
}
a[i]=tmp;
}
public static <AnyType extends Comparable<? super AnyType>>
void heapsort(AnyType[] a){
@SuppressWarnings("unchecked")
//创建一个相同长度的数组
AnyType[] b=(AnyType[])new Comparable[a.length];
for(int i=a.length/2-1;i>=0;i--)
percDown(a,i,a.length);//对于所有不是叶子节点的节点进行向下过滤
for(int i=a.length-1;i>=0;i--)
{
AnyType f=swapReferences(a,0,i);//去除根节点,并把最后一个元素作为根节点值
b[i]=f;
percDown(a,0,i);//然后对根节点进行过滤
}
for(int i=0;i<a.length;i++){
a[i]=b[i];
}
}
private static <AnyType extends Comparable<? super AnyType>>
AnyType swapReferences(AnyType[] a, int start,int end){
AnyType result=a[start];
a[start]=a[end];
a[end]=result;
return result;
}
//找到左孩子
private static int leftChild(int i){
return 2*i+1;
}
private static <AnyType extends Comparable<? super AnyType>>
void percDown(AnyType[] a ,int i,int n){
int child;
AnyType tmp;
for(tmp=a[i];leftChild(i)<n;i=child){
child=leftChild(i);
if(child!=n-1&&a[child].compareTo(a[child+1])<0)
child++;
if(tmp.compareTo(a[child])<0)
a[i]=a[child];
else
break;
}
a[i]=tmp;
}
public static <AnyType extends Comparable<? super AnyType>>
void heapsort(AnyType[] a){
@SuppressWarnings("unchecked")
//创建一个相同长度的数组
AnyType[] b=(AnyType[])new Comparable[a.length];
for(int i=a.length/2-1;i>=0;i--)
percDown(a,i,a.length);//对于所有不是叶子节点的节点进行向下过滤
for(int i=a.length-1;i>=0;i--)
{
AnyType f=swapReferences(a,0,i);//去除根节点,并把最后一个元素作为根节点值
b[i]=f;
percDown(a,0,i);//然后对根节点进行过滤
}
for(int i=0;i<a.length;i++){
a[i]=b[i];
}
}
private static <AnyType extends Comparable<? super AnyType>>
AnyType swapReferences(AnyType[] a, int start,int end){
AnyType result=a[start];
a[start]=a[end];
a[end]=result;
return result;
}
}
测试:
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer[] nums=new Integer[]{1,5,1,6,2,7,3,5,2,8,3,4};
//Shellsort.shellsort(nums);
Heapsort.heapsort(nums);
for(Integer num:nums){
System.out.print(num+" ");
}
效果:
1 1 2 2 3 3 4 5 5 6 7 8
0 0
- 堆及堆排序
- 堆/堆排序特点
- 【二叉堆、堆排序】
- 二叉堆 & 堆排序
- 二叉堆 & 堆排序
- 堆与堆排序
- 堆与堆排序
- 堆与堆排序
- 堆与堆排序
- 堆与堆排序
- 堆与堆排序
- 堆和堆排序
- 堆排序(最大堆)
- 堆和堆排序
- 堆和堆排序
- 堆及堆排序
- 堆和堆排序
- 堆与堆排序
- 数据结构——八大排序算法理解
- python split() join()
- JavaScript实现类的private、public
- Spring MVC高级配置
- eclipse中Tomcat启动之后访问不了
- 堆排序
- cogs 728. [网络流24题] 最小路径覆盖问题
- sys.argv用法
- IntelliJ Idea 常用快捷键列表
- Cloudera Manager、CDH零基础入门、线路指导
- 代码注释:机器学习实战第7章 利用AdaBoost元算法提高分类性能
- 操作系统小练习3
- LeetCode
- ubuntu 16.04上对Python版本之间的切换(2.7\3.X)