Heap sorting code example of Java algorithm

Heap is a special complete binary tree, which is characterized by that all parent nodes are smaller than child nodes, or all parent nodes are larger than word nodes. The former is called the minimum heap and the latter is called the maximum heap.

For example, the following two:

So what does this feature do? Since the topic is heap sorting, it can certainly be used for sorting. If you want to sort by heap, you must first create a heap. If you sort the seven numbers 4 3 6 2 7 1 5 from small to large, you need to create a maximum heap with these seven numbers. Look at the code:

For the sequence in this example, from this Length / 2 to 1, three cycles were performed.

First round:

Second round:

Third round:

After adjustment, the current binary tree has met the characteristics of maximum heap and can be used to sort from small to large. The principle of heap sorting is to exchange the numbers of the top of the heap and the last node, that is, put the maximum number at the end of the array, and then perform the adjustment process for the first n-1 numbers except the maximum number to make it conform to the maximum heap characteristics. Repeat the above process until there is only one number left in the heap.

The time complexity of heap sort is the same as the average time complexity of quick sort, which is O (nlogn).

summary

The above is all about the heap sorting code example of Java algorithm in this paper. I hope it will be helpful to you. Interested friends can continue to refer to this site: code examples of various sorting algorithms implemented in Java, running out of the maze of Java genetic algorithm, etc. if you have any questions, you can leave a message at any time. Xiaobian will reply to you in time. Thank you for your support!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>