数据结构之堆排序

这个堆排序是借鉴http://blog.csdn.net/hguisu/article/details/7776068 这个博文所改,首先要感谢博主的精彩分享。

简介:

堆排序分为两步骤:1、构建一个初始堆(完全二叉树、大顶堆)    

                         2、不断交换堆顶与堆尾的元素,那么堆底的元素都是排好的

                         3、 调用adjustheap,将树—>堆

                         4、debug的使用,出现数组溢出问题:

 

 

package database;

public class heapSort {
    public static void adjustheap(int[] H, int s, int len) {                         //对每个小子树都进行堆排
        int tmp = 0;
        int child = 2 * s + 1;
        while (child < len) {                                                                   // len代表的是元素的位置
            if ((child + 1 < len) && (H[child] < H[child + 1])) {
                child++;   //  这里不用交换大小,直接将地址指向child+1即可
            }
            if (H[s] < H[child]) {
                tmp = H[s];
                H[s] = H[child];
                H[child] = tmp;   // 可以封装成一个函数
            } else {
                break;
            }
        }
        for (int i : H) {
            System.out.print(i + " ");
        }
        System.out.println("");
    }

    public static void buildingHeap(int[] H, int len) {                 //通过控制小子树的父节点,来进行控制整个堆的排序
        for (int s = (len - 1) / 2; s >= 0; s--) {
            adjustheap(H, s, len);
        }
    }

    public static void heapSort(int[] H) {                                   //交换堆顶与未经排序的最后的元素;
        buildingHeap(H, H.length );
        for (int i = H.length-1 ; i > 0; i--) {                                      //代表的是数组的长度
                int tmp = H[i];
                H[i] = H[0];
                H[0] = tmp;
                buildingHeap(H, i);
        }
    }

    public static void main(String[] args) {
        int[] H = { 1, 3, 54, 23, 78, 21, 13, 444, 122, 432, 8,2000};
        heapSort(H);
        for (int i : H) {
            System.out.print(i + " ");     //foreach   ,对数组的输出
        }
    }
}

 

所以,堆排序也是在自身上做调换,不用开辟新的空间(没有用到递归)。

 

posted @ 2015-12-15 15:41  wangb021  阅读(314)  评论(0编辑  收藏  举报