자바 최대 더미 구현 (배열 방식)

1979 단어 알고리즘
최대 더미, 최소 더 미 는 우선 대기 열 이 고 매번 꺼 내 는 요 소 는 최대 또는 최소 입 니 다.본 블 로 그 는 주로 배열 로 최대 더 미 를 실현 하고 최소 더 미 를 실현 하 는 원리 도 마찬가지다.물론 list 집합 으로 요 소 를 저장 할 수 있어 편리 하고 용량 의 크기 를 미리 설정 하지 않 아 도 된다.그래도 원생 의 방식 으로 이 루 고 싶 습 니 다.구체 적 인 주석 은 이미 코드 에 끼 워 넣 었 다.
package heap;

//         
public class MaxHeap {
	private int[] a;      //    
	private int size;     //       
	
	public MaxHeap(int initCapacity) {
		a=new int[initCapacity+1];   //   0  "  ", 1      
		a[0]=Integer.MAX_VALUE;   //    
		size=0;
	}
	
	//  
	public boolean isEmpty() {
		return size==0;
	}
	//  
	public boolean isFull() {
		return size==a.length-1;
	}
	
	//    
	public boolean insert(int data) {
		//       ,     
		if(isFull()) {
			System.out.println("  ,    ");
			return false;
		}
		a[++size]=data;
		for(int i=size;a[i]>a[i/2];i/=2) {
			int t=a[i];
			a[i]=a[i/2];  //            
			a[i/2]=t;
		}
		return true;
	}
	
	//      ,      
	public int deleteMax() {
		//    
		if(isEmpty()) {
			System.out.println(" ,      ");
			return -1;
		}
		//     
		int maxValue=a[1];
		int tmp=a[size--];
		//              ,        
		int parent=1,child=2;
		for(;parent*2<=size;parent=child) {
			child=parent*2;  //   
			//        ,            
			if(childa[child]) {
				child++;  //child          
			}
			//             ,     
			if(tmp>a[child]) {
				break;
			}else {
				int t=a[parent];
				a[parent]=a[child];
				a[child]=t;	
			}
		}
		//         parent  
		a[parent]=tmp;	
		return maxValue;
	}
	
	//     
	public void print() {
		if(isEmpty()) {
			System.out.println("   ");
			return;
		}
		for(int i=1;i<=size;i++) {
			System.out.print(a[i]+" ");
		}
		System.out.println();
	}
	
	public static void main(String[] args) {
		int[] b= {10,8,4,5,9,15,11,20};
		MaxHeap heap=new MaxHeap(b.length);
		for(int i=0;i

좋은 웹페이지 즐겨찾기