堆排序

ぐ巨炮叔叔 提交于 2020-01-15 01:13:45
import java.util.Arrays;

public class Test {

    private static void swap(int[] arr, int a, int b) {
        int tmp = arr[a];
        arr[a] = arr[b];
        arr[b] = tmp;
    }

    private static int parent(int i) {
        return (i - 1) >> 1;
    }

    private static int left(int i) {
        return (i << 1) + 1;
    }

    private static int right(int i) {
        return (i << 1) + 2;
    }

    private static void insert(int[] arr, int i) {
        int data = arr[i];
        int parent;
        while (i != 0) {
            parent = parent(i);

            if (arr[parent] < data) {
                arr[i] = arr[parent];
                i = parent;
            } else {
                break;
            }
        }
        arr[i] = data;
    }

    private static void heapify(int[] arr, int length) {
        int i = 0, left, right;
        while (i < length && (left = left(i)) < length) {
            int max = i;
            if (arr[left] > arr[max]) {
                max = left;
            }

            if ((right = right(i)) < length && arr[right] > arr[max]) {
                max = right;
            }

            if (i != max) {
                swap(arr, i, max);
                i = max;
            } else {
                break;
            }
        }
    }

    private static void heapSort(int[] arr) {
        for (int i = 1; i < arr.length; ++ i) {
            insert(arr, i);
        }

        for (int i = arr.length - 1; i > 0; -- i) {
            swap(arr, 0, i);
            heapify(arr, i);
        }
    }

    public static void main(String[] args) {
        int[] arr = {2, 3, 4, 5, 7, 0, 1, 2, 10, 9};
        heapSort(arr);
        Arrays.stream(arr).forEach(System.out::println);
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!