java常用排序算法之堆排序

JAVA常用排序算法之堆排序

 

算法的平均时间复杂度为O(n×log(n))

实现的代码如下:

 

package com.beibei.risk.sort;

/**
 * desc:堆排序算法,使用大根堆
 * Created by zhai on 2017/9/7.
 */
public class HeadSort {
    public static void main(String[] args) {
        int[] arr = {32, 12, 99, 28, 66, 57};
        headSort(arr);
        //print(arr);
    }


    //堆排序的算法
    private static void headSort(int[] arr) {
        int[] head = new int[arr.length];
        //先构建无序堆
        for (int i = 0; i < arr.length; i++) {
            head[i] = arr[i];
        }
        buildHead(head, 0);


    }

    //建立有序堆的方法
    private static void buildHead(int[] head, int index) {
        if (index >= head.length) {
            return;
        }
        int temp = 0;
        if (2 * index + 1 >= head.length) {
            //do nothing
        } else if (2 * index + 2 >= head.length) {
            if (compare(head[2 * index + 1], head[index])) {
                temp = head[index];
                head[index] = head[2 * index + 2];
                head[2 * index + 2] = temp;
            }
        } else {
            if (compare(head[2 * index + 1], head[index]) || compare(head[2 * index + 2], head[index])) {
                if (compare(head[2 * index + 1], head[2 * index + 2])) {
                    temp = head[index];
                    head[index] = head[2 * index + 1];
                    head[2 * index + 1] = temp;


                } else {
                    temp = head[index];
                    head[index] = head[2 * index + 2];
                    head[2 * index + 2] = temp;
                }

            }

        }
        buildHead(head, index + 1);
    }

    //交换最大值的方法
    private static boolean compare(int a, int b) {
        return a > b ? true : false;
    }

    //输出数组的方法
    private static void print(int[] arr) {
        for (int i = 0; i < arr.length; i++)
            System.out.println(arr[i]);
    }


}

 

 

 

 

 

你可能感兴趣的:(基础知识笔记)