排序算法-堆排序20220314

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

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

代码:

import java.util.Arrays;

/**
 * 堆排序
 *
 * @author DepengZhang
 * @date 2021年07月30日 20:01
 */
public class HeapSort {

	/**
	 * 下沉调整
	 *
	 * @param array       待调整的堆
	 * @param parentIndex 要下沉的父节点
	 * @param length      堆的有效大小
	 */
	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;
	}

	/**
	 * 堆排序(升序)
	 *
	 * @param array 待调整的堆
	 */
	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));
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值