堆排序

来源:互联网 发布:詹姆斯总决赛数据科比 编辑:程序博客网 时间:2024/06/02 06:14
package heapsort;import java.util.Arrays;public class HS1 {public static void main(String[] args) {int[] A={87,45,78,32,17,65,53,9,63};BuildHeap(A);System.out.println(Arrays.toString(A));}public static void BuildHeap(int A[]){int len=A.length;int index=len-1;int father;for(father=index/2-1;father>=0;father--){//父节点从中间向前面走AdjustDown(A, father, index);//第二个参数是父节点,第三个是最后一个元素的下标}for(int i=A.length-1;i>=0;i--){swap(A,0,i);//将第一个()与最后一个交换位置,然后堆去掉最后一个AdjustDown(A, 0, i-1);}}public static void swap(int[] A,int a,int b){int c;c=A[a];A[a]=A[b];A[b]=c;}public static void AdjustDown(int A[],int fa,int index){int b=A[fa];for(int left=2*fa+1;left<=index;left=2*left+1){//i是左孩子if(left+1<=index&&A[left]<A[left+1]){//如果有右孩子则比较left++;}if(b>=A[left]){break;}else{A[fa]=A[left];fa=left;//修改k}}A[fa]=b;}}

1 0