【重温篇】八大排序——堆排序

完全二叉树

首先复习一下完全二叉树:数据从上到下,从左到右依次进行排列

堆排序

第一步

利用完全二叉树构建大顶堆

大顶堆:父节点的值大于或等于其左右孩子的值(构建方法如下)

1.定义一个parent游标,让parent游标从后往前移动,直到有孩子节点停下来

2.定义parent的左孩子child,判断左孩子是否为空,有孩子,一定会有左孩子

3.如果左孩子不为空,判断有没有右孩子,如果有有孩子,那么左右孩子进行对比,child游标指向左右孩子的最大值

4.父节点和子节点进行对比,如果父节点的值大,就让parent继续往前移动;如果父节点的值小,就让父子节点的值进行交换,父节点指向子节点,子节点指向其左右孩子的最大值,如果child没有孩子,parent不再往下指

5.不断重复2-4步,直到大顶堆构建完成

第二步

让堆顶元素和堆底元素进行互换,互换完成之后,堆底元素不再参与构建

第三步

不断重复一二两步

源码

复制代码
public class HeapSort {

	public static void main(String[] args) {
		
		int[] arr = new int[] {5,7,4,2,0,3,1,6};
		for(int p = arr.length-1;p >= 0;p--) {
			adjust(arr, p, arr.length);
		}
		
		//第二步
		for(int i = arr.length-1;i >= 0;i--) {
			int temp =arr[i];
			arr[i] = arr[0];
			arr[0] = temp;
			adjust(arr, 0, i);
		}
		
		System.out.println(Arrays.toString(arr));
		
	}
	public static void adjust(int[] arr,int parent,int length) {
		
		int Child = 2*parent+1;
		while(Child < length) {
			int rChild = Child +1;
			if(rChild < length && arr[rChild] > arr[Child]) {
				Child++;
			}
			
			if(arr[parent] < arr[Child]) {
				//父子节点进行交换
				int temp = arr[parent];
				arr[parent] = arr[Child];
				arr[Child] = temp;
				parent = Child;
				Child = 2*Child+1;
			}else {
				break;
			}
			
		}
	}
}
相关推荐
独好紫罗兰2 小时前
对python的再认识-基于数据结构进行-a003-列表-排序
开发语言·数据结构·python
wuhen_n2 小时前
JavaScript内置数据结构
开发语言·前端·javascript·数据结构
2401_841495642 小时前
【LeetCode刷题】二叉树的层序遍历
数据结构·python·算法·leetcode·二叉树··队列
独好紫罗兰3 小时前
对python的再认识-基于数据结构进行-a002-列表-列表推导式
开发语言·数据结构·python
2401_841495643 小时前
【LeetCode刷题】二叉树的直径
数据结构·python·算法·leetcode·二叉树··递归
数智工坊3 小时前
【数据结构-树与二叉树】4.5 线索二叉树
数据结构
数智工坊4 小时前
【数据结构-树与二叉树】4.3 二叉树的存储结构
数据结构
独好紫罗兰4 小时前
对python的再认识-基于数据结构进行-a004-列表-实用事务
开发语言·数据结构·python
铉铉这波能秀4 小时前
LeetCode Hot100数据结构背景知识之列表(List)Python2026新版
数据结构·leetcode·list
历程里程碑4 小时前
Linux20 : IO
linux·c语言·开发语言·数据结构·c++·算法