标签:
import java.util.Scanner ; public class HeapSort{ int[] h ; int n ; public void swap(int[] array, int x, int y){ //简单的交换函数; int t = array[x] ; array[x] = array[y] ; array[y] = t ; } public void siftDown(int i){ //下滤;一般在删除最小或最大元素后,将最后一个元素放到根节点的位置,进行下滤操作,以保持堆的堆序性; boolean flag = true ; while(2*i<=n && flag == true){ int t ; if (h[i]>h[i*2]) { t = i*2 ; }else{ t = i ; } if (i*2+1<=n) { if (h[t]>h[i*2+1]) { t = i*2+1 ; } } if (t!=i) { swap(h,i,t) ; i = t ; }else{ flag = false ; } } } public void siftDown02(int i){ //下滤操作,递归版本; if(2*i<=n){ int t ; if (h[i]>h[i*2]) { t = i*2 ; }else{ t = i ; } if (i*2+1<=n) { if (h[t]>h[i*2+1]) { t = i*2+1 ; } } if (t!=i) { swap(h,i,t) ; siftDown02(t) ; } } } public void siftUp(int i){ //上滤,一般在最后位置插入新元素后,通过上滤操作,以维持堆的堆序性; boolean flag = true ; if (i!=1) { while(i!=1 && flag == true){ if (h[i] < h[i/2]) { swap(h,i,i/2) ; }else{ flag = false ; } i = i/2 ; } } } public void siftUp02(int i){ //上滤操作,递归版本; if (i!=1) { if (h[i] < h[i/2]) { swap(h,i,i/2) ; siftUp(i/2) ; } } } public void insert(int value){ //插入操作; n++ ; h[n] = value ; siftUp(n) ; } public void createHeap(){ //创建堆; for (int i=n/2;i>=1;i--) { siftDown02(i) ; } } public int deleteMin(){ //删除最小元素; int t = h[1] ; h[1] = h[n] ; n-- ; siftDown02(1) ; return t ; } public static void main(String[] args){ //测试; HeapSort hs = new HeapSort() ; hs.h= new int[101] ; System.out.println("please input ‘n =‘:") ; Scanner sc = new Scanner(System.in) ; int num = sc.nextInt() ; for (int i=1;i<=num;i++) { hs.h[i] = sc.nextInt() ; } hs.n = num ; hs.createHeap() ; hs.insert(45) ; while(hs.n>=1){ System.out.print(hs.deleteMin() + " ") ; } System.out.println() ; } }
标签:
原文地址:http://www.cnblogs.com/lshl/p/5925802.html