算法导论——堆排序(Heap-Sort)

//堆排序(Heap-Sort)
/*
 * 堆排序大顶堆(小顶堆)
 * 1:初次建堆 Build_MAAX_HEAP();
 * 2:堆的维护 MAX_HEAPIFY();
 * 
 * 性质(大顶堆):
 * 	   堆中除根元素之外每个元素都满足 A[PARENT(i)] >= A[i]
 */

import java.util.Random;
import java.util.Scanner;

public class Main {
	
	public static void main(String[] args){
		MAX_HEAP T = new MAX_HEAP();
		Scanner in = new Scanner(System.in);
		System.out.println("堆的大小:");
		while(in.hasNext()){
			T.Init(in.nextInt());
			T.HEAP_SORT();
			System.out.println("\n堆的大小:");
		}
		in.close();
	}
}


class MAX_HEAP{
	
	private  int length;
	private  int size;
	private  int[] temp;
	
	public void Init(int n){
		length = size = n;
		temp = new int[length + 1];
		Random  rand = new Random();
		for(int i = 1; i <= length; ++i){
				temp[i] = rand.nextInt(1000);
				System.out.printf("%d ",temp[i]);
		}
		
	}
	
	public void HEAP_SORT(){
		Build_MAAX_HEAP();
		System.out.println();
		for(int i = 1; i <= length; ++i){
			//System.out.printf("%3d ",temp[1]);
			Swap(temp,1,size);
			--size;
			MAX_HEAPIFY(1);
		}
		for(int i = 1; i <= length; ++i){
			System.out.printf("%d ",temp[i]);
		}
	}
	
	public void Build_MAAX_HEAP(){
		for(int i = length>>1; i >= 1; --i){
			MAX_HEAPIFY(i);
		}
	}
	
	public void MAX_HEAPIFY(int n){
		int left = n<<1; 
		int right = left|1;
		int largest = n;
		if(left <= size&&temp[left] > temp[n])  largest = left;
		if(right <= size&&temp[right] > temp[largest]) largest = right;
		if(largest != n) {
			Swap(temp,n,largest);
			MAX_HEAPIFY(largest);
		}
	}
	
	public void Swap(int[] t,int a,int b){
		int val = t[a]; t[a] = t[b]; t[b] = val;
	}
	
}

你可能感兴趣的:(基础算法)