堆(算法导论 part1 foundations, chapter 6 heapsort)

本文介绍了一种使用C++实现的堆排序算法,包括初始化数组、构建最大堆、堆排序过程及最终排序结果展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<time.h>
using namespace std;

const int AD = 6;
int arr[AD];

void initializeArray(int arr[], int n){
 srand(time(0));
 for(int i=0;i<n;i++){
  arr[i] = rand()%400;
 }
}

void swap(int& a, int&b){
 int temp = a;
 a = b;
 b = temp;
}

void printArray(int arr[], int n){
 for(int i=0; i<n; i++){
  cout<<arr[i]<<" ";
 }
 cout<<endl;
}

//left, right are max heap, join arr[index] in
void max_heapify_recursive(int arr[], int heapSize, int index){
 int left = (index <<1) +1;
 int right = (index<<1) +2;
 int largest = index;
 if(left<heapSize && arr[left]>arr[index]){
  largest = left;
 }if(right<heapSize && arr[right] > arr[largest]){
  largest = right;
 }
 if(largest != index){
  swap(arr[largest],arr[index]);
  max_heapify_recursive(arr,heapSize,largest);
 }
}

void max_heapify_iterator(int arr[], int heapSize, int index){
 int left = (index<<1)+1;
 int right = (index<<1) +2;
 int largest = index;
 while(left<heapSize){// has child
  if(left<heapSize && arr[left] > arr[index]){
   largest = left;
  }if(right<heapSize && arr[right] > arr[largest]){
   largest = right;
  }
  if(largest == index){
   break;
  }else{
   swap(arr[index],arr[largest]);
   index = largest;
   left = (index<<1)+1;
   right = (index<<1)+2;
   largest = index;
  }

 }
}
//max_heapify downward from the first internal node to 0
void build_max_heap(int arr[], int n){
 for(int i= n/2-1; i>=0; i--){
  max_heapify_iterator(arr,n,i);
 }
}


void heapSort(int arr[], int n){
 build_max_heap(arr,n);
 int heapSize = n;
 for(int i=n-1; i>0; i--){
  swap(arr[i],arr[0]);
  max_heapify_iterator(arr,--heapSize,0);

 }
}
void main(){
 initializeArray(arr,AD);
 printArray(arr,AD);

 //build_max_heap(arr,AD);
 heapSort(arr,AD);
 printArray(arr,AD);
}

共同进步
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值