Swift implementation of the heap sort algorithm code example _swift

Source: Internet
Author: User

Algorithm idea
Heap sorting utilizes the feature of the maximum (or minimum) keyword for the maximum heap (or small Gan) heap top record, making it easy to select the record of the largest (or smallest) keyword in the current unordered area.
1. The basic idea of using the maximum heap sort
(1) First the initial file R[1..N] into a maximum heap, this heap is the initial unordered area
(2) The maximum record of the r[1] (that is, the heap top) and the last record of the disordered region are exchanged, thus obtaining a new r[n r[1..n-1] and an ordered region r[n, and satisfying the R[1..n-1].keys≤r[n].key
(3) Since the exchange of new root r[1] may violate the heap nature, the current unordered area r[1..n-1 should be adjusted to heap. The r[1..n-1] is then exchanged with the largest record of the keyword r[1] and the last record of the interval r[n-1], resulting in a new unordered region r[1..n-2 and an ordered area r[n-1. N], and still satisfies the relationship r[1..n-2].keys≤r[n-1 ... N].keys, also adjust the r[1..n-2] to the heap.
......
Until the unordered area has only one element.
2. The basic operation of the maximum heap sorting algorithm:
(1) Build a heap, build the heap is the process of constantly adjusting the heap, starting from the LEN/2 to adjust, until the first node, where Len is the number of elements in the heap. The process of building a heap is a linear process, the process of invoking the adjustment heap from LEN/2 to 0 is the equivalent of O (H1) +o (H2) ... +o (HLEN/2) where h represents the depth of the node, LEN/2 represents the number of nodes, this is a summation process, and the result is a linear O (n).
(2) Adjustment heap: The adjustment heap is used during the build heap, and it is used in the heap sorting process. The idea is to compare node I and its child node left (i), right (i), select the three largest (or smallest), if the maximum (small) value is not node I but it's a child node, there interaction node I and the node, and then call the adjustment heap process, this is a recursive process. The process time complexity of the adjustment heap is related to the depth of the heap and is a LGN operation because it is adjusted along the depth direction.
(3) Heap sorting: Heap sorting is done using the two processes above. The first is to build the heap from the elements. The root node of the heap is then removed (typically in exchange with the last node), the previous Len-1 node is continued for the heap adjustment process, and then the root node is removed so that all nodes are removed. The time complexity of the heap sort process is O (NLGN). Because the time complexity of the heap is O (n) (called once), the time complexity of the adjustment heap is LGN, the n-1 times are invoked, so the time complexity of the heap sort is O (NLGN) [2]
attention
(1) Just do n-1, select the larger n-1 keyword that can make the file increment order.
(2) Sorting with small Gan is similar to using the maximum heap, except that the order result is descending order. Heap sorting and direct selection ordering the opposite: at any time the unordered region in the heap sort is always before the ordered region, and the ordered region is gradually extended to the whole vector at the end of the original vector.

Swift Example
(1) Ascending sort based on maximum heap implementation

Func initheap (InOut A: [Int]) {for var i = (a.count-1)/2; I >= 0;-I. {ADJUSTMAXHEAP (&a, Len:a.count, PA RENTNODEINDEX:I)} func adjustmaxheap (InOut A: [Int], Len:int, parentnodeindex:int) {//If Len <= 0, indicating that the unordered area has shrunk  Small to 0 guard Len > 1 else {return}//parent node's left and right child's index let Leftchildindex = 2 * parentnodeindex + 1///If not even the left child,
 
 There must be no right child, that means no more down. Guard Leftchildindex < Len else {return} let Rightchildindex = 2 * parentnodeindex + 2 Index to record the children that need to be exchanged with the parent node var targetindex =-1//If there is no right child, but the left child, can only choose left child if Rightchildindex > len {targetindex = Left-Hand Childindex} else {//left and right children have, you need to find the largest targetindex = A[leftchildindex] > a[rightchildindex]? leftchildindex: Rightchildindex}///Only the child is larger than the parent node, you need to Exchange if A[TARGETINDEX] > A[parentnodeindex] {Let temp = A[targetindex] A [Targetindex] = A[parentnodeindex] a[parentnodeindex] = temp//Due to the exchange, may destroy the nature of the new Shishi, so you need to adjust to a[targetindex] as the parent node of the subtree, so The properties of the Adjustmaxheap (&a, Len:len, Parentnodeindex:targetindex}} func Maxheapsort (InOut A: [Int]) {guard A.count > 1 else {R Eturn} initheap (&a) for var i = a.count-1; i > 0; ----I//every trip will be the top of the stack to the last position in the specified range if a[0] > a[i] {Let temp = a[0] a[0] = a[i] a[i] = temp} print (a Print (I-1)//Ordered area length +1, and unordered area length-1, continue to shrink the unordered area, so i-1//heap top is always at No. 0 position, so the parent node adjustment from the top of the heap can be adjustmaxheap (&a, len:i-1,
 parentnodeindex:0) print (a)}}

&NBSP
(2) sort based on minimum heap descending

Func initheap (InOut A: [Int]) {for var i = (a.count-1)/2; I >= 0;-I. {ADJUSTMINHEAP (&a, Len:a.count, PA RENTNODEINDEX:I)} func adjustminheap (InOut A: [Int], Len:int, parentnodeindex:int) {//If Len <= 0, indicating that the unordered area has shrunk  Small to 0 guard Len > 1 else {return}//parent node's left and right child's index let Leftchildindex = 2 * parentnodeindex + 1///If not even the left child,
 
 There must be no right child, that means no more down. Guard Leftchildindex < Len else {return} let Rightchildindex = 2 * parentnodeindex + 2 Index to record the children that need to be exchanged with the parent node var targetindex =-1//If there is no right child, but the left child, can only choose left child if Rightchildindex > len {targetindex = Left-Hand Childindex} else {//left and right children have, you need to find the largest targetindex = A[leftchildindex] < A[rightchildindex]? Leftchildindex: Rightchildindex}///Only the child is larger than the parent node, you need to exchange if A[TARGETINDEX] < A[parentnodeindex] {Let temp = A[targetindex] A [Targetindex] = A[parentnodeindex] a[parentnodeindex] = temp//Due to the exchange, may destroy the nature of the new Shishi, so you need to adjust to a[targetindex] as the parent node of the subtree, so The properties of the Adjustminheap (&a, Len:len, Parentnodeindex:targetindex}} func Minheapsort (InOut A: [Int]) {guard A.count > 1 else {R Eturn} initheap (&a) for var i = a.count-1; i > 0;
    ----I//every trip will be the top of the stack to the last position in the specified range if a[0] < A[i] {Let temp = a[0] a[0] = a[i] a[i] = temp} else { return//Can be directly exited, because it's all ordered.//Ordered area length +1, and unordered area length-1, continue to shrink unordered area, so i-1//heap top is always in position No. 0, so the parent node adjustment from the top of the heap can be adjustminheap (
 &a, Len:i-1, parentnodeindex:0)}

Test:

var arr = [5, 3, 8, 6, 4]
//var arr = [89,-7,999,-89,7,0,-888,7,-7]
maxheapsort (&arr)
 
print (arr)
 
//Play Print log as follows:
[4, 6, 5, 3, 8] 3 [6, 4, 5, 3,
8]
 
[3, 4, 5, 6, 8]
2 [5, 4
, 3, 6, 8]
 
[3, 4, 5, 8]
   1
[3, 4, 5, 6, 8] [3, 4, 5, 6,
 
]
8
[0, 3, 4, 5, 6]
 
[8, 3, 4, 5, 6]

Related Article

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.