堆排序的一些基本操作
package bin1;
import java.util.Arrays;
//1、建立一个大根堆
public class TestHeap {
public int[] elem;
public int usedSize;
public TestHeap(){
this.elem=new int[10];
this.usedSize=0;
}
public void adjustDown(int root){
int parent=root;
int child=2*parent+1;
//判断parent是否有孩子
while (child<this.usedSize){
//判断parent是否有右孩子,并且左孩子小于右孩子
if(child+1<this.usedSize && this.elem[child]<this.elem[child+1]){
child=child+1;
}
//若孩子结点大于父节点,交换
if(this.elem[child]>this.elem[parent]){
int temp=this.elem[child];
this.elem[child]=this.elem[parent];
this.elem[parent]=temp;
parent=child;
child=2*parent+1;
}else {
break;
}
}
}
//建立大根堆
public void createHeap(int[] array){
for (int i = 0; i < array.length; i++) {
this.elem[i]=array[i];
this.usedSize++;
}
for (int i = (this.usedSize-1-1)/2; i >= 0; i--) {
adjustDown(i);
}
}
//打印
public void show() {
for (int i = 0; i < this.usedSize; i++) {
System.out.print(this.elem[i] +" ");
}
System.out.println();
}
//2、大根堆入队操作
//向上调整
public void AdjustUp(int child) {
int parent = (child-1)/2;
while (child > 0) {
if(this.elem[child] > this.elem[parent]) {
int tmp = this.elem[child];
this.elem[child] = this.elem[parent];
this.elem[parent] = tmp;
child = parent;
parent = (child-1)/2;
}else {
break;
}
}
}
//入队操作
public void pushHeap(int val) {
if(isFull()) {
this.elem = Arrays.copyOf(this.elem, this.elem.length*2);
}
//先放到最后位置
this.elem[this.usedSize] = val;
this.usedSize++;
//开始向上调整
AdjustUp(this.usedSize-1);
}
public boolean isFull() {
return this.usedSize == this.elem.length;
}
//3、大根堆出队操作
//将最后一个结点和第一个结点交换,其他都为大根堆,此时只需要调整0号下标的元素
public void popHeap(){
if(isEmpty()){
return;
}
int temp=this.elem[0];
this.elem[0]=this.elem[this.usedSize-1];
this.elem[this.usedSize-1]=temp;
this.usedSize--;
adjustDown(0);
}
public boolean isEmpty(){
return this.usedSize==0;
}
//4、获得队首元素
public int getHeapTop(){
if(isEmpty()){
return -1;
}
return this.elem[0];
}
//5、将大根堆从小到大排序
public void sortHeap(){
int end=this.usedSize-1;
while (end>0) {
int temp = this.elem[end];
this.elem[end] = this.elem[0];
this.elem[0] = temp;
adjustDown(0, end);
end--;
}
}
public void adjustDown(int root,int len){
int parent=root;
int child=2*parent+1;
//判断parent是否有孩子
while (child<len){
//判断parent是否有右孩子,并且左孩子小于右孩子
if(child+1<len && this.elem[child]<this.elem[child+1]){
child=child+1;
}
//若孩子结点大于父节点,交换
if(this.elem[child]>this.elem[parent]){
int temp=this.elem[child];
this.elem[child]=this.elem[parent];
this.elem[parent]=temp;
parent=child;
child=2*parent+1;
}else {
break;
}
}
}
}