堆排序
2017-03-28 23:55
169 查看
基本思想:
堆排序(Heap Sort)就是利用堆(假设是大顶堆)进行排序的方法。它的基本思想是,将待排序的序列构造成一个大顶堆。此时,整个序列的最大值就是堆顶的根节点。将它移走(其实就是将其与堆数组的末尾元素交换,此时末尾元素就是最大值),然后将剩余的n-1个序列重新构造成一个堆,这样就会得到n个元素中的次大值,如此反复执行,便能得到一个有序序列了。程序示例
我们使用对拼排序对a={40,60,30,80,50,20,90,20,10,70}进行排序package com.xxt.heap_sort; import java.util.Arrays; /** * 堆排序 * @author 13983 * */ public class Sort { public static void main(String[] args) { int[] a={40,60,30,80,50,20,90,20,10,70}; HeapSort(a); System.out.println(Arrays.toString(a)); } private static void HeapSort(int a[]) { int i; for(i=a.length/2-1;i>=0;i--){ HeapAdjust(a,i,a.length-1); //建造大顶堆 } for(i=a.length-1;i>0;i--){ swap(a,0,i); HeapAdjust(a,0,i-1); } } private static void swap(int[] a, int m, int n) { //交换函数 int temp; temp=a[m]; a[m]=a ; a =temp; } private static void HeapAdjust(int[] a, int m, int n) { int temp,j; temp=a[m]; for(j=2*m+1;j<=n;j=j*2+1){//根据二叉树的性质: m为根节点 则2m为根节点的左孩子 if(j<n&&a[j]<a[j+1]){ j++; } if(temp>a[j]){ break; } a[m]=a[j]; m=j; } a[m]=temp; } }