java实现堆排序

package com.algorithm.tree;

import java.util.Arrays;

public class Heap<T extends Comparable> {
	private T[] heap;
	private int size;
	private T[] sortedArray;
	
	public Heap(T[] heap){     						/*建大顶堆*/
		this.heap=heap;
		size=heap.length;
		for(int i=size/2;i>=0;i--){             	/*size/2 是第一个叶子节点的位置*/
			heapAdjust(i,size);
		}
	}
	
	public void heapAdjust(int begin,int size){		/*begin表示要调整的子树在数组中的起始位置,size表示整个堆的大小*/
		int max=begin;
		if((2*begin+1<size)&&(heap[max].compareTo(heap[2*begin+1])<0)) max=2*begin+1;
		if((2*begin+2<size)&&(heap[max].compareTo(heap[2*begin+2])<0)) max=2*begin+2;
		if(max!=begin){
			T tempt;
			tempt=heap[begin];
			heap[begin]=heap[max];
			heap[max]=tempt;
			heapAdjust(max,size);
		}
	}
	
	public void heapSort(){
		for(int i=size-1;i>0;i--){
			T tempt;
			tempt=heap[0];
			heap[0]=heap[i];
			heap[i]=tempt;
			heapAdjust(0,i);
		}
		sortedArray=heap;
	}
	
	public T[] getSortedArray() {
		return sortedArray;
	}


	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Integer[] heap=new Integer[]{-8,0,9,8,7,6,10,4,3,2,1};
		Heap<Integer> h=new Heap<>(heap);
		System.out.println("初始堆:");
		System.out.println(Arrays.toString(heap));
		h.heapSort();
		System.out.println("排序后");
		System.out.println(Arrays.toString(h.getSortedArray()));
	}

}


 

输出结果:

初始堆:
[10, 8, 9, 4, 7, 6, -8, 0, 3, 2, 1]
排序后
[-8, 0, 1, 2, 3, 4, 6, 7, 8, 9, 10]

猜你喜欢

转载自blog.csdn.net/u012334071/article/details/41125999