public class HeapSortCls{
public HeapSortCls(int[] lst) {
// TODO Auto-generated constructor stub
this.lst = lst;
this.len = lst.length;
}
public void createHeap(){
int startIndex = (lst.length -1)/2;
//int startIndex = lst.length-1;
for(int i=startIndex; i>=0; i--){
adjustHeap(i, lst.length-1);
}
}
private void adjustHeap(int k, int lastIndex){
while(2*k+1 <= lastIndex){
int i = 2*k+1;
if(2*k+2 <= lastIndex && lst[i] < lst[i+1])
i++;
if(2*k+1 <= lastIndex && lst[k] <lst[i])
exch(k, i);
k = i;
}
}
public void heapSort(){
for (int i = lst.length-1; i >= 0 ; i--) {
adjustHeap(0, i);
exch(0, i);
}
}
private void exch(int i, int j){
int tmp = lst[i];
lst[i] = lst[j];
lst[j] = tmp;
}
}
堆排序
最新推荐文章于 2023-09-21 13:21:58 发布