| 1 | package cn.cwblue.heap; |
| 2 | |
| 3 | public class HeapSort { |
| 4 | public static void heapSort(int[] arr) { |
| 5 | if (arr == null || arr.length < 2) { |
| 6 | return; |
| 7 | } |
| 8 | int heapSize = arr.length; |
| 9 | for (int i = arr.length - 1; i >= 0; i--) { |
| 10 | heapify(arr, i, heapSize); |
| 11 | } |
| 12 | swap(arr, 0, --heapSize); |
| 13 | while (heapSize > 0) { |
| 14 | heapify(arr, 0, heapSize); |
| 15 | swap(arr, 0, --heapSize); |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | private static void heapify(int[] arr, int index, int heapSize) { |
| 20 | int left = index * 2 + 1; |
| 21 | while (left < heapSize) { |
| 22 | int largest = left + 1 < heapSize ? (arr[left] < arr[left + 1] ? left + 1 : left) : left; |
| 23 | largest = arr[index] < arr[largest] ? largest : index; |
| 24 | if (largest == index) { |
| 25 | return; |
| 26 | } |
| 27 | swap(arr, largest, index); |
| 28 | index = largest; |
| 29 | left = index * 2 + 1; |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | private static void swap(int[] arr, int i, int j) { |
| 34 | int temp = arr[i]; |
| 35 | arr[i] = arr[j]; |
| 36 | arr[j] = temp; |
| 37 | } |
| 38 | |
| 39 | public static void main(String[] args) { |
| 40 | int[] arr = {1,9,7,3,6,4,8,2,5}; |
| 41 | heapSort(arr); |
| 42 | for (int i : arr) { |
| 43 | System.out.print(i + " "); |
| 44 | } |
| 45 | } |
| 46 | } |
nothing calls this directly
no outgoing calls
no test coverage detected