zoukankan      html  css  js  c++  java
  • 数据结构之堆排序

    这个堆排序是借鉴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   ,对数组的输出
            }
        }
    }

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

    态度决定行为,行为决定习惯,习惯决定性格,性格决定命运
  • 相关阅读:
    JavaScript学习笔记(三十八) 复制属性继承
    每天一道逻辑思维题
    动态规划(4):求子数组最大和
    30天自制操作系统第四天学习笔记
    UVA 1344 Tian Ji -- The Horse Racing
    Word隐藏回车符技巧
    Apache Thrift
    Android更改桌面应用程序launcher的两种方式
    Java语言实现简单FTP软件------>FTP软件效果图预览之下载功能(二)
    Java Collection
  • 原文地址:https://www.cnblogs.com/neversayno/p/5048510.html
Copyright © 2011-2022 走看看