数据结构与算法学习笔记——堆排序

/**********************************************************************
* Copyright(C):
* Filename    : heapsort.c
* Author      :
* Version     :
* Date        :
* Description :
**********************************************************************/

#include "heapsort.h"


//------------------------------------------
// MaxHeapify(ElementType A[], int i, int heap_size){
// maintain the max-heap property 
// 
//
void MaxHeapify(ElementType A[], int i, int heap_size){
	int l = LEFT(i);
	int r = RIGHT(i);
	int largest = i;

	if ( l < heap_size-1 && A[l] > A[largest] ){
		largest = l;
	}
	if ( r < heap_size-1 && A[r] > A[largest] ){
		largest = r;
	}

	if ( largest != i ){
		ElementType a = A[ i ];
		A[ i ] = A[ largest ];
		A[ largest ] = a;

		MaxHeapify(A,largest,heap_size);
	}
}


//------------------------------------------
// BuildMaxHeap(ElementType A[], int N)
// Build max-heap
//
//
void BuildMaxHeap(ElementType A[], int N){
	int i;
	int heap_size = N;
	for (i=(N-1)/2; i>=0; i--){
		MaxHeapify(A,i,heap_size);
	}
}


//------------------------------------------
// HeapSort(ElementType A[], int N)
// heap sort algorithm
//
//
void HeapSort(ElementType A[], int N){
	int i;
	ElementType tmp;
	BuildMaxHeap(A,N);
	for (i=N-1; i>=1; i--){
		tmp = A[ 0 ];
		A[ 0 ] = A[ i ];
		A[ i ] = tmp;
		N--;
		MaxHeapify(A,0,N);
	}
}


/***********************************************************************
* Copyright(C):
* Filename    : heapsort.h
* Author      :
* Version     :
* Date        :
* Description :
***********************************************************************/

#ifndef ALGRTHM_HEAP_SORT_H
#define ALGRTHM_HEAP_SORT_H

#define LEFT(x)     ((x)<<1);
#define RIGHT(x)    (((x)<<1)+1)

typedef int ElementType;

//-------API function declaration--------------------

void HeapSort(ElementType A[], int N);

#endif // ALGRTHM_HEAP_SORT_H


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值