栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

算法 排序 堆排序

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

算法 排序 堆排序

根据自己命名习惯与方便理解进行实现快速排序,仅做记录,后续完善。

void maxHeapify(vector& nums, int index, int heapSize)
{
	int left = index*2+1;
	int right = index*2+2;
	int maxIndex = index;

	if( left < heapSize && nums[maxIndex] < nums[left] )
		maxIndex = left; 
	if( right < heapSize && nums[maxIndex] < nums[right] )
		maxIndex = right;
	if(maxIndex != index)
	{
		swap(nums[index], nums[maxIndex]);
		maxHeapify(nums, maxIndex, heapSize);
	}
}              

void buildMaxHeapify(vector& nums, int heapSize)
{
	//从下而上构造最大堆
	for(int i=heapSize/2; i>=0 ; i--)
	{
		maxHeapify(nums, i, heapSize);  
	}
}

void heapSort(vector& nums)
{
	int heapSize = nums.size();
	buildMaxHeapify(nums, heapSize);  
	
	//swap将每次排序后的最大值放置到当前队尾,形成从小到大排序
	for(int i=nums.size()-1; i>=1; i--)
	{
		swap(nums[0], nums[i]);
		heapSize--;
		maxHeapify(nums, 0, heapSize);
	}
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/860006.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号