数据结构几大排序(六)——堆排序

建立大根堆,写两个方法,一个sift()调整,一个是堆排序heapSort(),需要注意的是实际排序时要从下标1开始,因为涉及父节点与孩子节点的编号关系,那么从0开始是不合理的

Java

/**
 * @author LiuZhiguo
 * @date 2019/6/16 15:18
 */
public class HeapSort {
    public static void sift(int[] R, int low, int high) {
        int i=low, j=2*i;
        int temp = R[i];
        while (j <= high) {
            if (j < high &&R[j] < R[j+1])
                ++j;
            if (temp < R[j]) {
                R[i] = R[j];
                i = j;
                j = 2 * i;
            }
            else
                break;
        }
        R[i] = temp;
    }
    public static void heapSort(int R[], int n) {
        int i;
        int temp;
        for (i = n/2;i>=1;--i)
            sift(R, i, n-1);
        for (i =n-1;i >=2;--i) {
            temp = R[1];
            R[1] = R[i];
            R[i] = temp;
            sift(R,1, i-1);
        }
    }
    public static void main(String[] args) {
        int[] R = {-1,10,7,2,4,7,62,3,4,2,1,8,9,19};
        heapSort(R, R.length);
        System.out.println(R);
        for (int i=1;i<R.length;i++)
            System.out.println(R[i]);
    }
}

Python 

class HeapSort:
    def sift(self, nums, low, high):
        i = low
        j = 2 * i
        temp = nums[i]
        while j <= high:
            if j < high and nums[j] < nums[j+1]:
                j += 1
            if nums[j] > temp:
                nums[i] = nums[j]
                i = j
                j = i * 2
            else:
                break
        nums[i] = temp
    def heapSort(self, nums):
        n = len(nums)
        for i in range((n-1)//2, 0, -1):
            self.sift(nums, i, n-1)
            i -= 1
        for i in range(n-1, 0, -1):
            temp = nums[i]
            nums[i] = nums[1]
            nums[1] = temp
            self.sift(nums, 1, i-1)
        return nums

if __name__ == '__main__':
    test = HeapSort()
    nums = [-1, 10, 7, 2, 4, 7, 62, 3, 4, 2, 1, 8, 9, 19]
    test.heapSort(nums)
    print(nums)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值