用java实现,给出一个记录序列,用堆排序的方法将其进行升序排列,并且输出结果
时间: 2024-05-05 07:19:17 浏览: 17
当然,我会按照你的要求回答你的问题,以下是 Java 实现堆排序的代码,用于对给定的记录序列进行升序排列,并输出结果:
```java
public class HeapSort {
public static void sort(int[] arr) {
int n = arr.length;
// Build max heap
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// Extract elements from heap one by one
for (int i = n - 1; i > 0; i--) {
// Move current root to end
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
// Call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
static void heapify(int[] arr, int n, int i) {
int largest = i; // Initialize largest as root
int l = 2 * i + 1; // Left child
int r = 2 * i + 2; // Right child
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root
if (largest != i) {
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
public static void main(String args[]) {
int arr[] = {12, 11, 13, 5, 6, 7};
sort(arr);
System.out.println("Sorted array:");
for (int i = 0; i < arr.length; ++i)
System.out.print(arr[i] + " ");
}
}
```
上述代码可以在给定记录序列的情况下进行堆排序,并输出升序排列的结果,希望可以帮到你!