数据结构与算法——Java实现 33.堆排序

刻意去找的东西,往往是找不到的。

天下万物的来和去,都有它的时间。

------ 24.10.10

使用堆进行排序

算法描述

1.heapify 建立大顶堆(所有结点的父元素大于子元素)

2.将堆顶与堆底交换(最大元素被交换到堆底),缩小并下潜调整堆

3.重复第二步直至堆里剩一个元素

代码实现

堆的各方法

java 复制代码
import java.util.Arrays;

public class MaxHeap {
    // 整数数组表示堆
    int[] array;
    int size;

    public MaxHeap(int capacity) {
        this.array = new int[capacity];
    }

    public MaxHeap(int[] array) {
        this.array = array;
        this.size = array.length;
        heapify();
    }

    // 建堆
    private void heapify(){
        // 索引0为起点,如何找到最后的非叶子节点  size / 2 - 1
        for (int i = size / 2 - 1; i >= 0; i--) {
            down(i);
        }
    }

    // 将parent索引处的元素下潜,与两个孩子中较大值进行交换,直至没有孩子或者没有孩子比它大
    public void down(int parent) {
        int left = 2*parent+1;
        int right = left+1;
        int max = parent;
        if(left < size && array[left] > array[max]){
            max = left;
        }
        if(right < size && array[right] > array[max]){
            max = right;
        }
        if(max != parent){ // 找到了一个更大的孩子
            swap(max,parent);
            down(max);
        }
    }

    // 交换两个索引处的元素
    public void swap(int i, int j){
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    // 获取堆顶元素
    // Returns:堆顶元素
    public int peek(){
        if(size == 0){
            return -1;
        }
        return array[0];
    }

    // 删除堆顶元素
    // Returns:堆顶元素
    public int poll(){
        if(size == 0){
            return -1;
        }
        int top = array[0];
        swap(0,size-1);
        size--;
        down(0);
        return top;
    }

/*     删除指定索引处的元素
       Params:index - 索引
       Returns:被删除元素

 */
    public int poll(int index){
        if(size == 0){
            return -1;
        }
        int delete = array[index];
        swap(index,size-1);
        size--;
        down(index);
        return delete;
    }

/*     替换堆顶元素
       Params:replaced - 新元素
*/
    public void replace(int replaced){
        array[0] = replaced;
        down(0);
    }

/*      堆的尾部添加元素
        Params:offered - 新元素
        Returns:是否添加成功
 */
    public boolean offer(int offered){
        if(size == array.length){
            return false;
        }
        up(offered);
        size++;
        return true;
    }

    /*
        将offered元素上浮:直至offered小于父元素或者上浮到堆顶
        Returns:新加入的元素
     */
    private void up(int offered) {
        int child = size;
        while (child > 0){
            int parent = (child-1) / 2;
            if(array[child] > array[parent]){
                array[child] = array[parent];
            }else {
                break;
            }
            child = parent;
        }
        array[child] = offered;
    }

    public static void main(String[] args) {
        int[] array = {1,2,3,4,5,6,7};
        MaxHeap maxHeap = new MaxHeap(array);
        System.out.println(Arrays.toString(maxHeap.array));
        maxHeap.replace(5);
        System.out.println(Arrays.toString(maxHeap.array));
        maxHeap.poll(2);
        System.out.println(Arrays.toString(maxHeap.array));
        System.out.println(maxHeap.peek());
        maxHeap.poll();
        System.out.println(Arrays.toString(maxHeap.array));
        System.out.println(maxHeap.offer(5));
        System.out.println(Arrays.toString(maxHeap.array));
        maxHeap.poll();
        System.out.println(Arrays.toString(maxHeap.array));
        maxHeap.peek();
        maxHeap.offer(9);
        System.out.println(Arrays.toString(maxHeap.array));
    }
}

堆排序的实现

调用堆中方法,按照给出的堆排序算法思路,进行排序

java 复制代码
import java.util.Arrays;

public class Sort {
    public static void main(String[] args) {
        int[] arr = {2,3,1,7,6,4,5};
        MaxHeap maxHeap = new MaxHeap(arr);
        System.out.println(Arrays.toString(maxHeap.array));

        while(maxHeap.size > 1){
            maxHeap.swap(0, maxHeap.size-1);
            maxHeap.size--;
            maxHeap.down(0);
        }
        System.out.println(Arrays.toString(maxHeap.array));
    }
}
相关推荐
hay_lee11 小时前
Spring AI实现对话聊天-流式输出
java·人工智能·ollama·spring ai
Hx_Ma1611 小时前
SpringBoot数据源自动管理
java·spring boot·spring
微小冷11 小时前
Rust异步编程详解
开发语言·rust·async·await·异步编程·tokio
SunnyDays101111 小时前
Java 高效实现 CSV 转 Excel
java·csv转excel
starfire_hit11 小时前
JAVAWEB根据前台请求获取用户IP
java·服务器·网络
fengxin_rou11 小时前
[Redis从零到精通|第四篇]:缓存穿透、雪崩、击穿
java·redis·缓存·mybatis·idea·多线程
A9better11 小时前
C++——不一样的I/O工具与名称空间
开发语言·c++·学习
像少年啦飞驰点、11 小时前
从零开始学 RabbitMQ:小白也能懂的消息队列实战指南
java·spring boot·微服务·消息队列·rabbitmq·异步编程
清水白石00811 小时前
《为什么说 deque 是 Python 滑动窗口的“隐藏神器”?深入解析双端队列的高效之道》
开发语言·python
杜子不疼.11 小时前
Ascend_C自定义算子开发
c语言·开发语言