如何在 Java 中对数组执行堆排序?
以下是堆排序(最大堆)的算法。
步骤 1 − 在堆的尾部创建一个新节点。
步骤 2 − 给新节点分配新值。
步骤 3 − 将此子节点的值与其父节点进行比较。
步骤 4 − 如果父节点的值小于子节点,则交换它们的位置。
步骤 5 − 重复步骤 3 和 4,直至堆属性成立。
示例
import java.util.Arrays;
import java.util.Scanner;
public class Heapsort {
public static void heapSort(int[] myArray, int length) {
int temp;
int size = length-1;
for (int i = (length / 2); i >= 0; i--) {
heapify(myArray, i, size);
};
for(int i= size; i>=0; i--) {
temp = myArray[0];
myArray[0] = myArray[size];
myArray[size] = temp;
size--;
heapify(myArray, 0, size);
}
System.out.println(Arrays.toString(myArray));
}
public static void heapify (int [] myArray, int i, int heapSize) {
int a = 2*i;
int b = 2*i+1;
int largestElement;
if (a<= heapSize && myArray[a] > myArray[i]) {
largestElement = a;
} else {
largestElement = i;
}
if (b <= heapSize && myArray[b] > myArray[largestElement]) {
largestElement = b;
}
if (largestElement != i) {
int temp = myArray[i];
myArray[i] = myArray[largestElement];
myArray[largestElement] = temp;
heapify(myArray, largestElement, heapSize);
}
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the size of the array :: ");
int size = scanner.nextInt();
System.out.println("Enter the elements of the array :: ");
int[] myArray = new int[size];
for(int i=0; i<size; i++) {
myArray[i] = scanner.nextInt();
}
heapSort(myArray, size);
}
}输出
Enter the size of the array :: 5 Enter the elements of the array :: 45 125 44 78 1 [1, 44, 45, 78, 125]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP