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

排序算法-堆排序20220314

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

排序算法-堆排序20220314

学习堆排序必须搞明白堆这个数据结构!!!

排序思路:
首先将待排序数组构建成最大堆,然后逐一将root放到末尾,堆的特性会将其第而大的数作为最大数上浮成root,最终产生有序数组。

代码:

import java.util.Arrays;


public class HeapSort {

	
	public static void downAdjust(int[] array, int parentIndex, int length) {
		// temp 保存父节点值,用于最后的赋值
		int temp = array[parentIndex];
		int childIndex = 2 * parentIndex + 1;
		while (childIndex < length) {
			// 如果有右孩子,且右孩子大于左孩子的值,则定位到右孩子
			if (childIndex + 1 < length && array[childIndex + 1] > array[childIndex]) {
				childIndex++;
			}
			// 如果父节点大于任何一个孩子的值,则直接跳出
			if (temp >= array[childIndex]) {
				break;
			}
			//无须真正交换,单向赋值即可
			array[parentIndex] = array[childIndex];
			parentIndex = childIndex;
			childIndex = 2 * childIndex + 1;
		}
		array[parentIndex] = temp;
	}

	
	public static void heapSort(int[] array) {
		//把无序数组构建成最大堆
		for (int i = (array.length - 2) / 2; i >= 0; i--) {
			downAdjust(array, i, array.length);
		}
		System.out.println(Arrays.toString(array));
		//循环删除堆顶元素,移到集合尾部,调整堆产生新的堆顶
		for (int i = array.length - 1; i > 0; i--) {
			// 最后1个元素和第1个元素进行交换,这个交换建议还是换成temp转,一旦数值一样此两个值将变成0
			array[i] = array[i] ^ array[0];
			array[0] = array[i] ^ array[0];
			array[i] = array[i] ^ array[0];
			// “下沉”调整最大堆
			downAdjust(array, 0, i);
		}
	}

	public static void main(String[] args) {
		int[] arr = new int[]{1, 3, 2, 6, 5, 7, 8, 9, 10, 0};
		heapSort(arr);
		System.out.println(Arrays.toString(arr));
	}
}

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

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

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