使用java写一个堆排序
时间: 2024-03-08 15:36:49 浏览: 45
Java实现堆排序
public class HeapSort {
public static void main(String[] args) {
int[] arr = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
heapSort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
public static void heapSort(int[] arr) {
if (arr == null || arr.length <= 1) {
return;
}
// 构建大根堆
buildMaxHeap(arr);
for (int i = arr.length - 1; i >= 1; i--) {
// 将堆顶元素与最后一个元素交换位置
swap(arr, 0, i);
// 调整堆
maxHeapify(arr, 0, i);
}
}
private static void buildMaxHeap(int[] arr) {
int len = arr.length;
for (int i = len / 2 - 1; i >= 0; i--) {
maxHeapify(arr, i, len);
}
}
private static void maxHeapify(int[] arr, int i, int len) {
int left = 2 * i + 1;
int right = 2 * i + 2;
int largest = i;
if (left < len && arr[left] > arr[largest]) {
largest = left;
}
if (right < len && arr[right] > arr[largest]) {
largest = right;
}
if (largest != i) {
swap(arr, i, largest);
maxHeapify(arr, largest, len);
}
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
阅读全文