随手笔记,写的不好见谅
个人理解堆
当前节点的值都小于(大于)它的左右节点堆可以实现优先队列,因为根节点的值最小(最大),取根节点即可堆用数组实现保存树的结构(数组的行与树的神),完全二叉树堆的性质如下. 当前节点的左节点为下标为i2+1,右节点下标为i2+2. 当前节点(不管左右节点)的父节点的下标为(i - 1)/2
图
Java实现堆
public class MaxHeap {
int arr
[];
int currentsize
;
public MaxHeap(){
arr
= new int[100];
currentsize
= 0;
}
public MaxHeap(int[] arr
, int n
){
this.arr
= arr
;
currentsize
= n
;
heapify(n
);
}
public void insert(int val
){
arr
[currentsize
] = val
;
percolateUp(currentsize
);
currentsize
++;
}
public int delMax(){
int tempmax
= arr
[0];
arr
[0] = arr
[--currentsize
];
percolateDown(currentsize
, 0);
arr
[currentsize
] = 0;
return tempmax
;
}
public void heapify(int n
){
for(int i
= n
/2 - 1; i
>= 0; i
--){
percolateDown(n
, i
);
}
}
public int percolateDown(int n
, int i
){
int j
;
while(i
!= (j
= ProperParent(n
, i
))){
swap(i
, j
);
i
= j
;
}
return i
;
}
public int percolateUp(int i
){
while(0 < i
){
int j
= (i
- 1) / 2;
if(arr
[i
] < arr
[j
]){
break;
}
swap(i
, j
);
i
= j
;
}
return i
;
}
public int[] heapSort(){
int newarr
[] = new int[currentsize
];
int idx
= 0;
while(currentsize
!= 0){
newarr
[idx
++] = delMax();
}
return newarr
;
}
public int ProperParent(int n
, int i
){
return RChildValid(n
, i
) ? Bigger(Bigger(i
, i
* 2 + 1), i
* 2 + 2) :
LChildValid(n
, i
) ? Bigger(i
, i
* 2 + 1) : i
;
}
public boolean RChildValid(int n
, int i
){
if(i
* 2 + 2 < n
){
return true;
}
return false;
}
public boolean LChildValid(int n
, int i
){
if(i
* 2 + 1 < n
){
return true;
}
return false;
}
public int Bigger(int i
, int j
){
if(j
< currentsize
){
return arr
[i
] > arr
[j
] ? i
: j
;
}
return i
;
}
public void swap(int i
, int j
){
int temp
= arr
[i
];
arr
[i
] = arr
[j
];
arr
[j
] = temp
;
}
public void display(){
for(int i
: arr
){
if(i
== 0){
break;
}
System
.out
.print(i
+" ");
}
System
.out
.println();
}
public static void main(String
[] args
) {
MaxHeap maxhp
= new MaxHeap();
maxhp
.insert(16);
maxhp
.insert(59);
maxhp
.insert(4);
maxhp
.insert(28);
maxhp
.insert(44);
maxhp
.insert(31);
maxhp
.insert(32);
maxhp
.insert(14);
System
.out
.println("建堆后的数组值:");
maxhp
.display();
maxhp
.delMax();
System
.out
.println("删除最大值后的数组值:");
maxhp
.display();
int arr
[] = {14, 31, 4, 16, 28, 32, 44, 59};
MaxHeap maxhp2
= new MaxHeap(arr
, arr
.length
);
System
.out
.println("建堆后的数组值:");
maxhp2
.display();
System
.out
.println("归并排序的数组值:");
int arr2
[] = maxhp2
.heapSort();
for(int j
: arr2
){
System
.out
.print(j
+" ");
}
}
}
运行结果
转载请注明原文地址:https://blackberry.8miu.com/read-1923.html