算法之排序:堆排序
阿新 • • 發佈:2018-12-10
amp aps i++ index size clas left ins pub
public static void swap(int[] arr, int i, int j) { int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } public static void heapInsert(int[] arr, int index) { while (arr[index] > arr[(index - 1) / 2]) { swap(arr, index, (index - 1) / 2); index = (index - 1) / 2; } } public static void heapify(int arr[], int index, int size) { while (index * 2 + 1 <= size) { int left = index * 2 + 1; int right = left + 1; int largest = right <= size && arr[right] > arr[left] ? right : left; largest = arr[largest] > arr[index] ? largest : index; if (largest == index) { break; } swap(arr,largest,index); index=left; } } public static void heapSort(int arr[]) { if (arr == null || arr.length < 2) { return; } for (int i = 0; i < arr.length; i++) { heapInsert(arr, i); } int size = arr.length-1; while (size > 0) { swap(arr, 0, size--); heapify(arr, 0, size); } }
算法之排序:堆排序