838. Heapsort(Module HeapSort) Described by Java

Now we can note module of HeapSort.
The problem.Problem in AcWing


The problem is to print the minimal k number, it’s easy to change the output when we need. The Time Complexity is O(nlogn).
And the Code :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter pw = new PrintWriter(System.out);
    static int N = 100010;
    static int h[] = new int[N], size, n, k;

    public static void main(String[] args) throws IOException {
        String ss[] = br.readLine().split(" ");
        n = Integer.parseInt(ss[0]);
        k = Integer.parseInt(ss[1]);
        String[] s = br.readLine().split(" ");
        for (int i = 1; i <= n; i++) h[i] = Integer.parseInt(s[i - 1]);
        size = n;

        for (int i = n >> 1; i >= 0; i-- ) down(i);

        while (k-- > 0) {
            pw.print(h[1] + " ");
            h[1] = h[size--];
            down(1);
        }
        pw.flush();
        br.close();
    }

    private static void down(int x) {
        int t = x;
        if ((x << 1) <= size && h[x << 1] < h[t]) t = (x << 1);
        if ((x << 1) + 1 <= size && h[(x << 1) + 1] < h[t]) t = (x << 1) + 1;
        if (t != x) {
            int temp = h[x];
            h[x] = h[t];
            h[t] = temp;
            down(t);
        }
    }
}
堆排序是一种高效的排序算法,它利用了堆的数据结构来实现排序。堆是一个完全二叉树,具有以下性质:对于任意节点 i,其父节点的值小于等于子节点的值。 堆排序的基本思路如下: 1. 构建最大堆:将待排序的数组看作是一个完全二叉树,从最后一个非叶子节点开始,依次向上调整每个节点,使得以该节点为根的子树满足最大堆的性质。 2. 将堆顶元素与最后一个元素交换:将最大堆的堆顶元素(即数组的第一个元素)与数组最后一个元素交换位置,此时最大元素就位于数组的最后。 3. 调整堆:将剩余元素重新调整为最大堆。 4. 重复步骤 2 和步骤 3,直到所有元素都排序完成。 以下是堆排序的 C++ 代码实现: ```cpp #include <iostream> using namespace std; // 调整以 root 为根的子树为最大堆 void heapify(int arr[], int n, int root) { int largest = root; // 假设根节点最大 int left = 2 * root + 1; // 左子节点索引 int right = 2 * root + 2; // 右子节点索引 // 若左子节点大于根节点,更新最大值索引 if (left < n && arr[left] > arr[largest]) { largest = left; } // 若右子节点大于最大值节点,更新最大值索引 if (right < n && arr[right] > arr[largest]) { largest = right; } // 若最大值不是根节点,交换根节点和最大值 if (largest != root) { swap(arr[root], arr[largest]); // 递归调整交换后的子树 heapify(arr, n, largest); } } void heapSort(int arr[], int n) { // 构建最大堆 for (int i = n / 2 - 1; i >= 0; i--) { heapify(arr, n, i); } // 逐步取出最大值,调整堆 for (int i = n - 1; i > 0; i--) { swap(arr[0], arr[i]); heapify(arr, i, 0); } } int main() { int arr[] = {4, 10, 3, 5, 1}; int n = sizeof(arr) / sizeof(arr[0]); heapSort(arr, n); cout << "Sorted array: "; for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; return 0; } ``` 以上就是堆排序的基本思路和实现方法。堆排序的时间复杂度为 O(nlogn),其中 n 为数组的长度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值