排序算法——堆排序:大根堆、小根堆

堆排序:

利用二叉树进行排序,有大根堆排序和小根堆排序

大根堆(升序):

int[] arr = {3, 2, 5, 4, 7, 0, 8};//
按顺序可以构造出一棵二叉树
      3
   2     5
 4   7 0   8
我们可以得出以下规律:
i为父节点下标  则它的子节点下标应该为(如果存在的话)2*i+12*i+2
i为子节点时  则它的父节点下标应该为(i-1)/2
当待排序数的个数为n时,则第一个叶子节点的下标为n/2,最后一个非叶子节点下标为n/2 - 1 

**我们需要保证父节点一定比子节点大**
变为:
      3
   2     8
 4   7 0   5
变为:
      3
   7     8
 4   2 0   5
变为:
      8
   7     3
 4   2 0   5
.......

我们从最后一个非叶子节点遍历调整使得所有节点满足规则,当我们调整完所有非叶子节点后可以保证根节点一定是最大的,
这时我们将根节点与末尾节点交换,下一次只用对[0, arr.length()-1)再进行以上操作...显然我们可以发现这可以利用递归来轻松实现

代码实现:
/*
* 先将数组按顺序排列成一棵二叉树, 子节点找父节点-->(i-1)/2   父节点找子节点-->(i*2+1, i*2+2)
* 不断对这棵二叉树作大根堆的变换,根节点始终应该是最大值,做完变化后交换根节点与最后一个节点的值
* 下一次排除最后一个元素后对剩余元素再次进行变换(通过递归,减小边界值)
* */
private void sort(int[] nums, int bound) {//bound是待排序数组的长度
    if(bound == 0) return;
    for(int i = (bound / 2) - 1; i >= 0; i--) {
        int replace = 2 * i + 1;//需要与父节点交换的节点的下标先默认为左子节点因为右子节点可能不存在
        if((2 * i + 2) < bound && nums[replace] < nums[i * 2 + 2]) replace = 2 * i + 2;
        if(nums[i] < nums[replace]) swap(nums, i, replace);//父节点小再换
    }
    swap(nums, 0, bound - 1);//将根节点与最后一个叶子节点交换
    sort(nums, bound-1);
}

private static void swap(int[] nums, int index1, int index2) {
    int temp = nums[index1];
    nums[index1] = nums[index2];
    nums[index2] = temp;
}


小根堆(降序):

private void sort(int[] nums, int bound) {//bound是待排序数组的长度
	if(bound == 1) return;
	for(int i = (bound >> 1) - 1; i >= 0; i--) {
		int replace = 2 * i + 1;//需要与父节点交换的节点的下标先默认为左子节点因为右子节点可能不存在
        if((2 * i + 2) < bound && nums[replace] > nums[i * 2 + 2]) replace = 2 * i + 2;
        if(nums[i] > nums[replace]) swap(nums, i, replace);//父节点大再换
	}
	swap(nums, 0, bound - 1);//将根节点与最后一个叶子节点交换
    sort(nums, bound-1);
}

private static void swap(int[] nums, int index1, int index2) {
    int temp = nums[index1];
    nums[index1] = nums[index2];
    nums[index2] = temp;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值