Heap sorting and related operations

Source: Internet
Author: User

Heap sorting and related operations

Record the operations related to the heap.

Op 1:

'''@ data: the heap array@ p   : index of parent item @ n   : number of data@@ Swap p and it's son items, make p the largest of them'''def swapForMaxHeap(data, n, p):ls = p << 1 | 1rs = ls + 1# p has two sons or just leftif ls < n  or rs < n:if rs < n:if data[ls] < data[rs]: ls = rsif data[p] < data[ls]:data[p], data[ls] = data[ls], data[p]return lsreturn -1

The function above compares the value of the parent node represented by p with the value of its child node, and exchanges the node value with the child node with a large value to maximize the value of the parent node, and returns the index of the child node to which it is exchanged. If no exchange exists,-1 is returned.

Op 2:

'''@ data: the heap array@ p   : index of parent item @ n   : number of data@@ Swap p and it's son items, make p the smallest of them'''def swapForMinHeap(data, n, p):ls = p << 1 | 1rs = ls + 1# p has two sons or just leftif ls < n  or rs < n:if rs < n:if data[ls] > data[rs]: ls = rsif data[p] > data[ls]:data[p], data[ls] = data[ls], data[p]return lsreturn -1

Similar to the above function, it only takes a small node value.

Op 3:

def Swap(data, n, p, ls = 0):fun = {}fun[0] = swapForMaxHeapfun[1] = swapForMinHeapreturn fun[ls](data, n, p)

Encapsulate the above two functions. The ls parameter indicates the heap type, 0 indicates the large root heap, and 1 indicates the small root heap.

Op 4:

'''@ data : the heap array@ i    : the start index to be fixUp@ n    : the number of data@ ls   : if 0, it is a max heap, otherwise, min one@@ '''def fixUp(data, i, n, ls = 0):if n <= 1: returnif i <= 0 or i >= n: returnp = (i - 1) >> 1while p >= 0:Swap(data, n, p, ls)p = (p - 1) >> 1

The node tracing process is used for the insert operation. During the insertion, the value of the new node is first inserted to the end of the heap array, because the new node may violate the heap nature and needs to be adjusted up, until it is adjusted to the top.

Op 5:

def fixDown( data, i, n, ls = 0):if n <= 1: returnif i < 0 or i >= n: returnwhile i <= n - 1:index = Swap(data, n, i, ls)if index == -1: breaki = index
The sinking process of the node, used for deleting and creating the heap. The delete operation is only performed on the top of the heap, that is, the top element of the heap is deleted. During the deletion, the last element of the heap is exchanged with the top element of the heap. After the deletion, the new heap top element may violate the heap nature, so it needs to be adjusted down.

Op 6:

'''@ data: data array that adjust to be heap@ n   : number of data@ ls  : 0-max heap, 1- min heap'''def buildHeap(data, n, ls = 0):if n <= 1: returnfor i in xrange( (n >> 1) - 1, -1, -1):fixDown(data, i, n, ls)

The establishment of the heap does not need to start from 0, that is, to insert elements in the array into the empty heap one by one, because if there is no size limit on the size of the heap, the given array can also be regarded as a heap, but a messy heap. We only need to adjust these elements, that is, starting from the last non-leaf node, downward adjustment.

Op 7:

def insert(data, new_x, ls = 0):data.append(new_x)n = len( data )fixUp(data, n - 1, n , ls)

This is the insert operation. During the insert operation, the new elements are inserted to the end, and then traced back to conform to the nature of the heap.

Op 8:

def delete(data, n, ls = 0):if n <= 0: returnif n == 1:del data[0]returndata[0], data[-1] = data[-1], data[0]del data[-1]print datafixDown(data, 0, n - 1, ls)

The delete operation can be performed on the top of the heap. What about the vacancy after deletion? The most monotonous identity is the last node, because it certainly does not have any child node, and it will not disrupt the subscript, so we use it to exchange with the heap top, the purpose of the code is to explain the meaning of the exchange. In fact, you only need to assign the value of the last node to the heap top, that is, data [0] = data [-1]. Delete the last node. From top down.

Op 9:

def heapSort(data, n, ls = 0):if n <= 1: returnfor i in xrange(n - 1, -1, -1):data[i], data[0] = data[0], data[i]fixDown(data, 0, i, ls)data.reverse()print data

This is the sorting of heap sorting. Taking a small root heap as an example, the heap top is the smallest of the whole sequence, swap it with the last node, and then adjust it, the adjusted heap top is relatively minimal, and then swap.





Specific heap Sorting Algorithm

1. Definition of heap sorting
N key word sequences Kl, K2 ,..., Kn is called a heap, and only when the sequence meets the following properties (referred to as heap properties ):
(1) ki ≤ K2i and ki ≤ K2i + 1 or (2) Ki ≥ K2i and ki ≥ K2i + 1 (1 ≤ I ≤)

If we store the vector R [1 .. n] as a full binary tree storage structure, the heap is essentially a Complete Binary Tree that meets the following requirements: the keywords of any non-leaf node in the tree are not greater than (or not less) keywords of the left and right children (if any) nodes.
[Example] the keyword sequences (,) and (,) satisfy the heap properties (1) and (2) respectively, so they are all heap, the corresponding full binary tree is shown in the example of the small root heap and the example of the large root heap.

2. Large and small heaps
The keyword of the root node (also known as the heap top) is the heap of the smallest node keyword in the heap.
The keyword of the root node (also known as the heap top) is the publisher of all node keywords in the heap, known as the Big root heap.
Note:
① Any subtree In the heap is also a heap.
② The Heap discussed above is actually Binary Heap, which can be defined similarly.

3. Heap sorting features
HeapSort is a tree-based sorting method.
The characteristic of heap sorting is that during the sorting process, R [l .. n] As a Complete Binary Tree ordered storage structure, using the inherent relationship between the parent and child nodes in the Complete Binary Tree [see the binary tree ordered storage structure ], select the record with the maximum or minimum keyword in the unordered area.

4. Differences between heap sorting and direct insert sorting
Directly select the sort, In order .. n] to select the record with the smallest keyword. The record must be compared n-1 times, and then in R [2 .. n] in the selection of the minimum keyword record, and need to do a N-2 comparison. In fact, many comparisons in the next N-2 comparison may have been done in the previous n-1 comparison, but since these comparison results were not retained in the previous sort, therefore, these comparison operations are repeated during the next sorting.
Partial comparison results can be saved in a tree structure to reduce the number of comparisons.

5. Heap sorting
Heap sorting utilizes the largest (or least) keyword of the top record of a large root heap (or a small root heap) so that the largest (or least) keyword is selected in the current unordered area) keyword record becomes simple.

(1) the basic idea of sorting with big roots
① First build the initial file R [1. n] into a large root heap, which is the initial unordered Zone
② Then exchange the record R [1] (heap top) with the last record R [n] In the unordered zone, and obtain the new unordered zone R [1 .. n-1] And the ordered zone R [n], and meet the requirements of R [1 .. n-1]. keys ≤ R [n]. key
③ Because the new root R [1] After the swap may violate the heap nature, the R [1 .. n-1] of the unordered zone should be changed to the heap. Then re-set R [1 .. in n-1], the record R [1] with the largest keyword is exchanged with the last record R [n-1] In the interval, and a new unordered zone R [1 .. n-2] and ordered zone R [n-1 .. n], and still satisfies the relationship R [1 .. n-2]. keys ≤ R [n-1 .. n]. keys, also set R [1 .. n-2] adjusted to heap.
......
Until there is only one element in the unordered area.

(2) Basic operations on the Sorting Algorithm of the big root heap:
① Initialization operation: Create R [1. n] as the initial heap;
② Basic operations for sorting each trip: swap the top record R [1] of the unordered zone with the last record in the interval, then adjust the new unordered area to the heap (also weigh and build the heap ).
Note:
① The large n-1 keywords can be selected to sort the files in ascending order.
② Sorting with a small root heap is similar to using a large root heap, but the sorting result is descending and ordered. Opposite to Direct selection: at any time, unordered areas in heap sorting are always before the ordered areas, the ordered area gradually expands from the back to the end of the original vector to the end of the whole vector.

(3) Heap Sorting Algorithm:
Void ...... remaining full text>

What is heap sorting?

Heap sorting
1. Definition of heap
Heap is a string containing n keywords {k1, k2 ,..., Kn} sequence with the following features:
Ki <= k2i
And ki <= k2i + 1 (1 <= I <= n/2) (1)
Or
Ki> = k2i
And ki> = k2i + 1 (1 <= I <= n/2) (2)
Ki> = k2i
Satisfied type (1) is called a minimal heap, or a very small heap, or a small heap. Satisfied type (2) is called a very large heap, or a large heap. This section describes how to minimize heap.
Relationship between the heap and the Complete Binary Tree: the heap is a sequence of n elements (keywords) that satisfies the relationship between nodes in the Complete Binary Tree sequence storage (the relationship between the parent and child sequence numbers ).
17,28, 51,33, 62,96, 87,51 is a small top heap.
96,51, 87,33, 28,62, 51,17 is a big top heap

Binary heap
2. Basic heap sorting problems
Since the heap top element (keyword) is the smallest element, it is the smallest element of the sorting sequence. After the output, the other elements are adjusted to the heaps, the new heap top element is the second element of the sorting sequence. In this case, a disordered sequence can be changed to an ordered sequence through the heap. Therefore, the basic problem of heap sorting is:
(1) how to create a heap
(2) how to tune the heap
3. How to tune the heap
After switching the last element and the heap top element (equivalent to outputting the heap top element), from the heap top to the last and last elements, except the heap top element, all other elements comply with the heap definition. The attention method is used below to bring together all elements, including the top elements of the heap. Heheap Root
Void Sift (RecType R [], int I, int m)
{‖ Assume that each element in R [I + 1 .. m] satisfies the heap definition. This algorithm adjusts R [I] to make the sequence
The elements in R [I.. m] satisfy the properties of the heap.
R [0] = R [I]; ‖ temporary "root" record R [I]
For (j = 2 * I; j <= m; j * = 2) ‖ j <= m, R [2i] is the left child of R [I]
{If (j <m & R [j]. key <R [j + l]. key) j ++;
‖ If the right child of R [I] exists and the keyword is greater than the left child, j points to the right child of R [I]
If (R [0]. key <R [j]. key) ‖ the child node has a large keyword.
{R [I] = R [j]; ‖ change R [j] to the parent location
I = j; ‖ modify the currently adjusted Node
}
Else break; ‖ adjusted and exited the loop
} ‖
R [I] = R [0]; ‖ the adjusted node is initially placed in the correct position
} ‖ Sift

4. How to Build a heap
A Complete Binary Tree with n nodes is considered to comply with the heap definition. The number of the last Non-terminal node is n/2, the heap creation can be completed by calling the above commit method in sequence at the root node. Specific algorithms are placed in the following heap sorting algorithms.
5. Heap Sorting Algorithm
Void HeapSort (RecType R [], int n)
{‖ Perform heap sorting on the record sequence R [1 .. n.
For (I = n/2; I> 0; I --) ‖ build R [1. n] into a large top heap
Sift (R, I, n );
For (I = n; I & g ...... remaining full text>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.