# 数据结构之堆

public int left (int i){
return ((i+1)*2-1);
}
public int right (int i){
return ((i+1)*2);
}
public int parent (int i){
if(i==0)
return -1;
else
return (i-1)/2;
}

package com.java.day11;

/**
* Created by wangkaishuang on 18-4-17
*/
static int left(int i){
return ((i+1)*2-1);
}
static int right(int i){
return ((i+1)*2);
}
static int parent(int i){
if(i==0)
return -1;
else
return (i-1)/2;
}
//大根堆
static void maxHeapify(int[] a, int i, int heapLenth){
int l = left(i);
int r = right(i);
int largest = -1;

if(l<heapLenth && a[i]<(a[l])){
largest = l;
}
else
largest = i;
if(r<heapLenth && a[largest]<a[r]){
largest = r;
}
if(i != largest){
int temp = a[i];
a[i] = a[largest];
a[largest] = temp;
maxHeapify(a,largest,heapLenth);
}
}

//小根堆
void minHeapify(int[] a,int i,int heapLenth){
int l = left(i);
int r = right(i);
int smallest = -1;

if(l<heapLenth && a[i] > a[l]){
smallest= l;
}
else
smallest = i;
if(r<heapLenth && a[smallest]>(a[r])){
smallest = r;
}
if(i != smallest){
int temp = a[i];
a[i] = a[smallest];
a[smallest] = temp;
minHeapify(a,smallest,heapLenth);
}
}
//建堆
static void buildHeap(int[] a, int heapLenth){
int lenthParent = parent(heapLenth-1);

for(int i=lenthParent;i>=0;i--){
maxHeapify(a,i,heapLenth);
}
}
public static void main(String[] args){
int a[] ={1,3,5,7,9};
buildHeap(a,5);
for(int c : a)
System.out.println(c);
}

}