Home  >  Article  >  heapsort

heapsort

(*-*)浩
(*-*)浩Original
2019-06-03 09:46:012227browse

Heap sort

Heap sort is a sorting algorithm designed using the data structure of a heap. Heap sort is a selection sort. Its worst and best, The average time complexity is O(nlogn), which is also unstable sorting. First, let’s briefly understand the heap structure.

heapsort

Heap

A heap is a complete binary tree with the following properties: the value of each node is greater than or equal to its left and right children The value of a node is called a big top heap; or the value of each node is less than or equal to the value of its left and right child nodes, which is called a small top heap.

Recommended courses: PHP Tutorial.

As shown below:

heapsort

#At the same time, we number the nodes in the heap by layer and map this logical structure It looks like this in the array

heapsort

The array is logically a heap structure. We use a simple formula to describe the definition of the heap:

Large top heap: arr[i] >= arr[2i 1] && arr[i] >= arr[2i 2]

Small top heap: arr[i]

The basic idea of ​​heap sorting is:

Construct the sequence to be sorted into a big top Heap, at this time, the maximum value of the entire sequence is the root node at the top of the heap. Swap it with the last element, then the last value is the maximum value. Then reconstruct the remaining n-1 elements into a heap, so that the next smallest value of n elements will be obtained. If you execute this repeatedly, you can get an ordered sequence

The above is the detailed content of heapsort. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What is OpenCVNext article:What is OpenCV