This article mainly introduces the relevant code of Java heap sorting algorithm in detail, which has certain reference value. Interested friends can refer to it
Heap is an important type of data structure. Structure, understanding the concept and operation of "heap" can help us quickly master heap sorting.
The concept of heap
The heap is a special complete binary tree. If the value of all nodes in a complete binary tree is not less than its child nodes, it is called a large root heap (or large top heap); if the value of all nodes is not greater than its child nodes, it is called a small root heap (or small top heap). heap).
In the array (the root node is stored at subscript 0), it is easy to get the following formula (these two formulas are very important):
1. The node with subscript i , the coordinates of the parent node are (i-1)/2;
2. For the node whose subscript is i, the coordinates of the left child node are 2*i+1 and the right child node is 2*i+2.
Creation and maintenance of heap
The heap can support a variety of operations, but now we are only concerned about two issues:
1 .Given an unordered array, how to build it as a heap?
2. After deleting the top element of the heap, how to adjust the array into a new heap?
Let’s look at the second question first. Assume we already have a large root pile ready to go. Now we've deleted the root element, but haven't moved any other elements. Think about what happens: the root element is empty, but the other elements still maintain the heap nature. We can move the last element (codename A) to the position of the root element. If it is not a special case, the nature of the heap is destroyed. But this is only because A is smaller than one of its children. Therefore, we can swap the positions of A and this sub-element. If A is larger than all its sub-elements, the heap is adjusted; otherwise, the above process is repeated, and the A element continues to "sink" in the tree structure until the appropriate position is reached, and the array regains its heap properties. The above process is generally called "screening", and the direction is obviously top-down.
The same is true for deleting an element, and the same is true for inserting a new element. The difference is that we put the new element at the end and then compare it with its parent node, that is, bottom-up filtering.
So, how to solve the first problem?
Many of the data structure books I have read filter down from the first non-leaf node until the root element is filtered. This method is called "screening method" and requires looping to screen n/2 elements.
But we can also learn from the idea of "making something out of nothing". We can treat the first element as a heap and keep adding new elements to it. This method is called "insertion method" and requires the insertion of (n-1) elements in a loop.
Because the filtering method and the insertion method are different, the heaps they create for the same data are generally different.
After having a general understanding of the heap, heap sorting is a matter of course.
Algorithm Overview/Ideas
We need an ascending sequence, what should we do? We can build a min-heap and then output the root element each time. However, this method requires additional space (otherwise it will cause a large number of elements to be moved, and its complexity will soar to O(n^2)). What if we need to sort in place (i.e. O(n) space complexity is not allowed)?
There is a way. We can build a maximum heap, and then we output it backwards, outputting the maximum value at the last position, and outputting the second-largest value at the last position... Since the largest element output each time will free up the first space, we can just place Such elements require no additional space. Pretty idea, isn't it?
public class HeapSort { public static void main(String[] args) { int[] arr = { 50, 10, 90, 30, 70, 40, 80, 60, 20 }; System.out.println("排序之前:"); for (int i = 0; i < arr.length; i++) System.out.print(arr[i] + " "); // 堆排序 heapSort(arr); System.out.println(); System.out.println("排序之后:"); for (int i = 0; i < arr.length; i++) System.out.print(arr[i] + " "); } /** * 堆排序 */ private static void heapSort(int[] arr) { // 将待排序的序列构建成一个大顶堆 for (int i = arr.length / 2; i >= 0; i--) heapAdjust(arr, i, arr.length); // 逐步将每个最大值的根节点与末尾元素交换,并且再调整二叉树,使其成为大顶堆 for (int i = arr.length - 1; i > 0; i--) { swap(arr, 0, i); // 将堆顶记录和当前未经排序子序列的最后一个记录交换 heapAdjust(arr, 0, i); // 交换之后,需要重新检查堆是否符合大顶堆,不符合则要调整 } } /** * 构建堆的过程 * @param arr 需要排序的数组 * @param i 需要构建堆的根节点的序号 * @param n 数组的长度 */ private static void heapAdjust(int[] arr, int i, int n) { int child; int father; for (father = arr[i]; leftChild(i) < n; i = child) { child = leftChild(i); // 如果左子树小于右子树,则需要比较右子树和父节点 if (child != n - 1 && arr[child] < arr[child + 1]) child++; // 序号增1,指向右子树 // 如果父节点小于孩子结点,则需要交换 if (father < arr[child]) arr[i] = arr[child]; else break; // 大顶堆结构未被破坏,不需要调整 } arr[i] = father; } // 获取到左孩子结点 private static int leftChild(int i) { return 2 * i + 1; } // 交换元素位置 private static void swap(int[] arr, int index1, int index2) { int tmp = arr[index1]; arr[index1] = arr[index2]; arr[index2] = tmp; } }
The above is the detailed content of Example analysis of heap sort algorithm in Java. For more information, please follow other related articles on the PHP Chinese website!

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

Java'splatformindependenceallowsapplicationstorunonanyoperatingsystemwithaJVM.1)Singlecodebase:writeandcompileonceforallplatforms.2)Easyupdates:updatebytecodeforsimultaneousdeployment.3)Testingefficiency:testononeplatformforuniversalbehavior.4)Scalab

Java's platform independence is continuously enhanced through technologies such as JVM, JIT compilation, standardization, generics, lambda expressions and ProjectPanama. Since the 1990s, Java has evolved from basic JVM to high-performance modern JVM, ensuring consistency and efficiency of code across different platforms.

How does Java alleviate platform-specific problems? Java implements platform-independent through JVM and standard libraries. 1) Use bytecode and JVM to abstract the operating system differences; 2) The standard library provides cross-platform APIs, such as Paths class processing file paths, and Charset class processing character encoding; 3) Use configuration files and multi-platform testing in actual projects for optimization and debugging.

Java'splatformindependenceenhancesmicroservicesarchitecturebyofferingdeploymentflexibility,consistency,scalability,andportability.1)DeploymentflexibilityallowsmicroservicestorunonanyplatformwithaJVM.2)Consistencyacrossservicessimplifiesdevelopmentand

GraalVM enhances Java's platform independence in three ways: 1. Cross-language interoperability, allowing Java to seamlessly interoperate with other languages; 2. Independent runtime environment, compile Java programs into local executable files through GraalVMNativeImage; 3. Performance optimization, Graal compiler generates efficient machine code to improve the performance and consistency of Java programs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version
SublimeText3 Linux latest version

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version
Chinese version, very easy to use

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
