public class HeapSortTest{
@Test
public void test() {
List<Integer> list = new ArrayList<>();
for (int i = 1;i<=5;i++) {
list.add((new Object().hashCode())%50+1);
}
System.out.println(list.toString());
System.out.println(heapSortTest(list).toString());
}
/*
* 对于堆排序,每次从建好的大(小)顶堆里面取出最上面的元素,和数组的最后一个交换
* 然后数组长度减一从新建堆。循环以后,最后的得到的数组就是排序好的
*/
public List<Integer> heapSortTest(List<Integer> a){
for(int i = a.size();i > 1;i--){//注意边界值。updateHeap中的aNum最小值为2
//得到大顶堆
builtHeap(a, i);
//swap(a[0],a[i-1])
a.set(0,a.get(0)+a.get(i-1));
a.set(i-1,a.get(0)-a.get(i-1));
a.set(0,a.get(0)-a.get(i-1));
}
return a;
}
//建堆
public void builtHeap(List<Integer> a,int aNum){
for(int i = (aNum-1)/2; i >= 0; i--){//(aNum-1)/2 means the first not leafnode
updateHeap(a, i, aNum);//form the bottom to built the heap,and update constantly
}
}
//更新堆
public void updateHeap(List<Integer> a,int index,int aNum){
int l = 2*index+1;//left index
int r = 2*index+2;//right index
int largest = index;//root index for temp
if(l < aNum && a.get(l) > a.get(largest)) largest = l;//firstly make sure (l,r)<a.lenth
if(r < aNum && a.get(r) > a.get(largest)) largest = r;//max(a[l],a.[r],a.[largest])
if(largest != index){
//swap(a.get(largest),a.get(index))
a.set(largest,a.get(largest)+a.get(index));
a.set(index,a.get(largest)-a.get(index));
a.set(largest,a.get(largest)-a.get(index));
//交换时候,要保证左右子树依旧是堆
updateHeap(a, largest, aNum);
}
}
}
数据结构——堆(java)
最新推荐文章于 2023-05-10 23:56:23 发布