选择排序之堆排序(大顶堆)

RT


#include<iostream>
#define N 8
using namespace std;

void SiftAdjust(int *scr, int low, int high);
void HeapSort(int *scr, int n);
void Print(int *scr, int n);
void Swap(int *scr1, int *scr2);

int main()
{
    int scr[N] = {36, 48, 48, 90, 88, 80, 76, 99};

    cout<<"原始顺序:";
    Print(scr, N);
    HeapSort(scr, N);
    cout<<endl;


    cout<<"排序后顺序:";
    Print(scr, N);
    cout<<endl;

    return 0;
}

void SiftAdjust(int *scr, int low, int high)//大顶堆调整
{
    int f,i;

    for (f = low, i =2*low+1; i <= high; i = 2*i+1)
    {
        if (i < high && scr[i] < scr[i+1])
        {
            i++;
        }

        if (scr[i] <= scr[f])
        {
            break;
        }

        Swap(&scr[i], &scr[f]);

        f = i;
    }
}

void HeapSort(int *scr, int n)
{
    int i;

    for (i = (n-2)/2; i >= 0; i--)
    {//调整成大顶堆
        SiftAdjust(scr, i, n-1);
    }
    cout<<endl;
    cout<<"调整为大顶堆:";
    Print(scr, N);
    for (i = n-1; i > 0; i--)
    {//第i趟排序
        Swap(&scr[0], &scr[i]);//将堆顶元素与未经排序的子序列中的最后一个元素交换
        //cout<<endl;
       // Print(scr, N);
        SiftAdjust(scr, 0, i-1);//重新调整为大顶堆
        cout<<endl;
        cout<<"重新调整为大顶堆:";
        Print(scr, N);
    }
}

void Swap(int *scr1, int *scr2)
{
    *scr1 = *scr1 ^ *scr2;
    *scr2 = *scr2 ^ *scr1;
    *scr1 = *scr1 ^ *scr2;
}

void Print(int *scr, int n)
{
    int i;
    for (i = 0; i < n; i++)
    {
        cout<<scr[i]<<" ";
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要将大顶堆转换为小顶堆,可以按照以下步骤进行操作: 1. 首先,将大顶堆的根节点(最大值)与最后一个叶子节点进行交换。 2. 然后,将交换后的最后一个叶子节点移出堆。 3. 接下来,对根节点进行下沉操作(与其子节点中较小的那个进行交换),以维持小顶堆的性质。 4. 重复步骤2和3,直到所有节点都被移出堆。 具体的实现过程如下: 1. 假设要将大顶堆存储在数组中,根节点的索引为0。 2. 交换根节点与最后一个叶子节点,即将根节点的值与数组末尾元素交换。 3. 对根节点进行下沉操作,找到它与子节点中较小值的索引,然后将其交换。 4. 重复步骤2和3,直到所有节点都被移出堆。 以下是一个示例实现的伪代码: ``` # 将大顶堆转换为小顶堆 def convert_to_min_heap(heap): n = len(heap) # 从最后一个非叶子节点开始,依次向前处理 for i in range(n // 2 - 1, -1, -1): # 将当前节点下沉到合适位置 heapify(heap, n, i) return heap # 下沉操作 def heapify(heap, n, i): smallest = i left = 2 * i + 1 right = 2 * i + 2 # 找到左子节点和右子节点中的最小值 if left < n and heap[left] < heap[smallest]: smallest = left if right < n and heap[right] < heap[smallest]: smallest = right # 如果最小值不是当前节点,则将其与当前节点交换,并继续下沉 if smallest != i: heap[i], heap[smallest] = heap[smallest], heap[i] heapify(heap, n, smallest) ``` 此伪代码通过调用 `convert_to_min_heap` 函数,将输入的大顶堆转换为小顶堆。注意,此实现假设堆中已经存在数据,并且堆的大小为 n。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值