堆排序实现(java)

package com.zp.algorithm.basic;

import java.util.Arrays;

public class HeapSortDemo {
 
	//节点的左节点
	private static int left(int i)
	{
		return i<<1;
	}
	//节点的右节点
	private static int right(int i)
	{
		return (i<<1)+1;
	}
	//维持树的最大堆性质
	private static<AnyType extends Comparable<? super AnyType>> void max_heapify(AnyType[] a,int i)
	{
		int l = left(i);
		int r = right(i);
		int largest = 0;
		if(l<=a.length-1&&a[l].compareTo(a[i])>0)
		{
			largest = l;
		}else{
			largest = i;
		}
		if(r<=a.length-1&&a[r].compareTo(a[largest])>0)
		{
			largest = r;
		}
		if(largest!=i)
		{
			AnyType tmp = a[i];
			a[i] = a[largest];
			a[largest] = tmp;
			max_heapify(a, largest);
		}
		
	}
	private static<AnyType extends Comparable<? super AnyType>> void build_max_heap(AnyType[] a)
	{
		int heap_size = a.length - 1;
		for(int i = heap_size/2;i>0;i--)
		{
			max_heapify(a,i);
		}
	}
	private static<AnyType extends Comparable<? super AnyType>> AnyType[] heapsort(AnyType[] a)
	{
		build_max_heap(a);
		AnyType[] tmp = (AnyType[]) new Comparable[a.length-1];
		for(int i = a.length-1;i>0;i--)
		{
			swap(a, i, 1);
			tmp[i-1] = a[i];
			a = subArray(a);//
			max_heapify(a, 1);
		}
		return tmp;
	}
	private static <AnyType extends Comparable<? super AnyType>>void swap(AnyType[] a,int i,int j)
	{
		AnyType tmp = a[i];
		a[i] = a[j];
		a[j] = tmp;
	}
	private static <AnyType extends Comparable<? super AnyType>>AnyType[] subArray(AnyType[] a)
	{
		AnyType[] new_a = (AnyType[]) new Comparable[a.length -1];
		for(int i = 0;i<a.length-1;i++)
		{
			new_a[i] = a[i];
		}
		return new_a;
	}
	
	public static void main(String[] args) {
		Integer i[] = {0,16,4,10,14,7,9,3,2,8,1};
//		System.out.println(Arrays.toString(i));
//		build_max_heap(i);
//		
//		System.out.println(Arrays.toString(i));
//		max_heapify(i, 2);
//		System.out.println(Arrays.toString(i));
		System.out.println(Arrays.toString(heapsort(i)));
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值