1、什么是堆
堆可以看做是一个完全二叉树,可以将一个array[0……n-1]的数组的顺序的看成是一个堆,因此他具有如下特点
父节点Parent(i): parent(i)←A[floor((i−1)/2)]
左节点Left(i): left(i)←A[2∗i+1]
右节点Right(i): right(i)←A[2∗i+2]
1.1、大根堆
从根出发,每一个节点的左右节点都小于等于节点的值;
1.2、小根堆
从根出发,每一个节点的左右节点都大于等于节点的值;
2、算法
1、构造大根堆(从最后一个节点的父节点开始构造);
2、取出堆顶元素并合堆最后的节点对换位置;
3、去除堆尾的元素 剩下的堆继续构造大根堆(从上到下,从左到右开始构造);
3、代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| package com.xuecx.sort;
public class HeapSortUtil {
private int[] buildMaxHeap(int[] array) { int n = array.length; for (int i = (n - 1) / 2; i >= 0; i--) { adjustDownToUp(array, i, n); } return array; }
private void adjustDownToUp(int[] array, int k, int n) { int temp = array[k]; for (int i = 2 * k + 1; i < n - 1; i = 2 * i + 1) { if (i < n && array[i] < array[i + 1]) { i++; } if (temp > array[i]) { break; } else { array[k] = array[i]; k = i; } array[i] = temp; } }
public int[] heapSort(int[] array) { array = buildMaxHeap(array); for (int i = array.length-1; i > 1; i--) { int temp = array[0]; array[0] = array[i]; array[i] = temp; adjustDownToUp(array, 0, i); } return array; }
public static void main(String[] args) { HeapSortUtil heapSortUtil=new HeapSortUtil(); int[] array={11,21,6,7,23,18,15,4,13}; int[] ints =heapSortUtil.heapSort(array); for (int anInt : ints) { System.out.print(anInt+","); } System.out.println(); } }
|