HeapSort

Data Structures and Algorithm 专栏收录该内容
7 篇文章 0 订阅

GIF demonstration

在这里插入图片描述

Source code demonstration

import java.util.Arrays;

public class code03_HeapSort {
    public static void main(String[] args) {
        int[] array = generateRandomArray(100, 100);
        int[] test = copyArray(array);
        Arrays.sort(test);
        heapSort(array);
        compareArray(array, test);
    }

    public static void heapSort(int[] array) {
        if (array == null || array.length < 2) {
            return;
        }
        int heapSize = array.length;
        //O(N*long(N))
        for (int i = 0; i < array.length; i++) {
            heapInsert(array, i);
        }
        //O(N)
//        for (int i = array.length - 1; i >= 0; i--) {
//            heapify(array, i, array.length);
//        }
        swap(array, 0, --heapSize);
        while (heapSize > 0) {
            heapify(array, 0, heapSize);
            swap(array, 0, --heapSize);
        }

    }

    public static void heapInsert(int[] array, int index) {
        while (array[index] > array[(index - 1) / 2]) {
            swap(array, index, (index - 1) / 2);
            index = (index - 1) / 2;
        }
    }

    public static void heapify(int[] array, int index, int heapSize) {
        int left = (2 * index) + 1;
        while (left < heapSize) {
            int largest = (left + 1 < heapSize && array[left + 1] > array[left]) ? left + 1 : left;
            largest = array[largest] > array[index] ? largest : index;
            if (largest == index) {
                break;
            }
            swap(array, largest, index);
            index = largest;
            left = (2 * index) + 1;
        }
    }

    public static void swap(int[] array, int i, int j) {
        if (i == j) {
            return;
        }
        array[i] = array[i] ^ array[j];
        array[j] = array[i] ^ array[j];
        array[i] = array[i] ^ array[j];
    }

    public static int[] generateRandomArray(int maxSize, int maxValue) {
        int[] array = new int[(int) ((maxSize + 1) * Math.random())];
        for (int i = 0; i < array.length; i++) {
            array[i] = (int) (maxValue * Math.random());
        }
        return array;
    }

    public static void compareArray(int[] array1, int[] array2) {
        if (!Arrays.equals(array1, array2)) {
            System.out.println("No equals!!");
        } else {
            System.out.println("Success!!");
        }
    }

    public static int[] copyArray(int[] array) {
        int[] tmp = new int[array.length];
        System.arraycopy(array, 0, tmp, 0, array.length);
        return tmp;
    }
}
  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值