Go language standard Ku King (heap) encapsulation and heap sequencing implementation

Source: Internet
Author: User

The OOP, interface, interface combination of the Go language, the function and interface of the basic library, how to abstract design,
These things are very well presented in the Go Heap source code and the demo example processing.

In "Container/heap", its interface is defined as follows:

Type Interface Interface {      sort.  Interface      Push (x interface{})//Add x as Element len ()      Pop () interface{}   //Remove and return element Len ()- 1.  }  
I do not quite understand why this design, had to use the following methods to try to understand.
1. Use the test example to understand how it is used.
2. Try to restore the original scene, that is, the use of source integration to achieve a primitive heap sorting

Then through the comparison of the two, to slowly realize.

Test examples of Container/heap:

Package Mainimport ("Container/heap" "FMT" "sort")//An intheap is a min-heap of Ints.type intheap []intfunc (H intheap) Len  () int {return len (h)}func (H intheap) Less (i, J int) bool {return h[i] < H[j]}func (H intheap) Swap (i, J  int) {H[i], h[j] = H[j], H[i]}func (H *intheap) push (x interface{}) {//Push and POP use pointer receivers because  They modify the slice ' s length,//not just it contents.*h = append (*h, x. (int))}func (H *intheap) Pop () interface{} {old  : = *hn: = Len (old) x: = Old[n-1]*h = Old[0:n-1]return x}//This example inserts several ints to an intheap, checks the minimum,//and removes them in order of Priority.func main () {h: = &intheap{100,16,4,8,70,2,36,22,5,12}fmt. Println ("\nheap:") heap. Init (h) fmt. Printf ("Minimum:%d\n", (*H) [0])//for (POP) outputs the minimum value sequentially, which is equivalent to performing a heapsortfmt.println ("\nheap sort:") for H.len () > 0 {fmt. Printf ("%d", heap. Pop (h))}//add a new value and then output to see FMT. Println ("\npush (H, 3), then output heap look:") heap. Push (H, 3) for H.len () > 0 {fmt. Printf ("%d", hEap. Pop (h))}fmt. Println ("\ n use sort. Sort order: ") H2: = intheap{100,16,4,8,70,2,36,22,5,12} sort. Sort (H2) for _,v: = range H2 {FMT. Printf ("%d", v)}}/* output:-----------------------------------heap: Minimum: 2Heap sort:2 4 5 8 100Push (H, 3), then output heap Look at: 3 use sort. Sort order: 2 4 5 8 12 16 22 36 70 100*/

A custom class that implements the associated interface after it is handed to the heap. Init () to build the heap.
after the pop () from the heap, the data is removed from the heap.
The ascending order is determined by less ().
Custom classes can also be sorted directly with sort, because the interface is implemented.


And then look at the heap sort code I've manually integrated into the implementation:

Package Main//heap//author:xiong Chuan liang//date:2015-2-4import ("FMT") var (Heap = []int{100,16,4,8,70,2,36,22,5,12 }) Func main () {FMT. Println ("\ n array:") Print (heap) makeheap () fmt. Println ("\ n Build Tree:") Print (heap) fmt. Println ("\ n increase 90,30,1:") push (1) Print (heap) N: = Pop () fmt. Println ("\npop out the Minimum (", N, ") After:") the Print (heap) fmt. Println ("\nremove () Drop IDX is 3", "Heap[3-1", "After:") remove (3) the Print (heap) fmt. Println ("\nheapsort () After:") Heapsort () print (heap)}func print (arr []int) {for _,v: = Range arr {fmt.      Printf ("%d", v)}}//build heap func makeheap () {n: = Len (heap) for i: = n/2-1; I >= 0;i--{down (i, N)}}//from parent node to child node build heap//parent : I//left child:2*i+1//right child:2*i+2func down (i,n int) {//build minimum heap, parent less than two child node values for {J1: = 2*i + 1if j1 >= n | | J1 &lt ; 0 {//J1 < 0 after int overflowbreak}//find the smallest of two nodes (less:a<b) J: = J1//left childif J2: = J1 + 1; J2 < n &&! Less (J1, J2) {j = j2//= 2*i + 2//Right child}//then compare with parent node I, if the parent node is smaller than the minimum child node, break, otherwise swapif! Less (J, i) {Break}swap (i, j) i = j}}//a child node to a parent node in turn rebuilds the heap func up (j int) {for {i: = (j-1)/2//Parent If i = = J | |! Less (J, i) {//less (child, parent)! Less (9,5) = = TRUE//parent node is smaller than child node, meets minimum heap condition, breakbreak}//child node is smaller than parent node, swap swap (I, j) j = I}}func Push (x interface{}) {heap = append (  Heap, X. (int)) Up (Len (heap)-1) return}func pops () interface{} {n: = Len (heap)-1Swap (0, N) down (0, N) Old: =heapn = Len (old) x : = Old[n-1]heap = Old[0:n-1]return X}func Remove (i int) interface{} {n: = Len (heap)-1if n! = i {Swap (i, N) down (i, N) u P (i)}return Pop ()}func less (a, b int) Bool{return Heap[a] < Heap[b]func Swap (a, b int) {HEAP[A],HEAP[B] = Heap[b],heap[a] }func Heapsort () {//Ascending less (Heap[a] > Heap[b])//Max heap//Descending less (Heap[a] < heap[b])//Minimum heap for I: = Len (heap)-1; i > 0;i- -{//Remove the top element to the end of the array, then the remaining rebuild heap, loop swap (0, i) down (0, i)}}/* output:-----------------------------------array: 100 16 4 8 70 2 36 22 5 1 2 Build Tree: 2 5 4 8 12 100 36 22 16 70 Add 90,30,1:1 5 2 8 4 30Pop minimum (1) After: 2 5 4 8 12 30 36 22 16 70 90 1 00Remove () Drop IDX is 3 value 4 after: 4 5 8 16 12 30 36 90HeapSort () After: 100 90 70 36 30 22 16 12 8 5 4*/ 

The contrast between the two shows that container/heap, really, only and only a heap is encapsulated..
The uncertain, various needs of the custom-made things to the user to achieve.
It is only responsible for the core heap of this part of the thing.
The base library is refreshing, and the heap will no longer feel tied to your feet.

MAIL: [Email protected]

blog:http://blog.csdn.ent/xcl168






Go language standard Ku King (heap) encapsulation and heap sequencing implementation

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.