Implementation and application of sort package in go

Time:2020-1-26

Preface

The sort package of go language implements the sorting of built-in and user-defined types. Three basic sorting algorithms are implemented in the sort package: insert sorting, fast sorting and heap sorting. As in other languages, these three methods are not disclosed, and they are only used inside the sort package. Therefore, users do not need to consider the sorting method when sorting with the sort package. Sort.interface determines the sorting method Three methods of semantic: len() method to get the length of data set, less() method to compare the size of two elements, and swap() method to exchange the positions of two elements, then the data set can be sorted smoothly. Sort package will automatically select an efficient sorting algorithm according to the actual data.

Before I shared with you the method of sorting the collection of any type of elements by using the sort package in go language. For interested friends, please refer to this article: www.jb51.net/article/60893.htm

Here is a simple example of a sort package:

type Interface interface {
 //Returns the length of data to sort
 Len() int
 //Compare the data size corresponding to subscripts I and j, and control the ascending and descending order by yourself  
Less(i, j int) bool
 //Exchange the data corresponding to I, j
 Swap(i, j int)
}

Any type that implements sort.interface (generally a collection) can be sorted using the methods in the package. These methods require the index of the listed elements in the collection to be an integer.

Here I use the source code to explain the implementation directly:

1. Example in source code:

type Person struct {
 Name string
 Age int
}

type ByAge []Person
//If three methods in the sort interface are implemented, the sorting method can be used
func (a ByAge) Len() int   { return len(a) }
func (a ByAge) Swap(i, j int)  { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }

func Example() {
 people := []Person{
  {"Bob", 31},
  {"John", 42},
  {"Michael", 17},
  {"Jenny", 26},
 }

 fmt.Println(people)
 Sort. Sort (byage (people)) // the sort() method in the sort package is called here. Let's take a look at this method
 fmt.Println(people)

 // Output:
 // [Bob: 31 John: 42 Michael: 17 Jenny: 26]
 // [Michael: 17 Jenny: 26 Bob: 31 John: 42]
}

2. Sort (data interface) method

//The sort package only provides this public sorting method,
func Sort(data Interface) {
 // Switch to heapsort if depth of 2*ceil(lg(n+1)) is reached.
 //If the element depth reaches 2 * ceil (LG (n + 1)), heap sorting is selected
 n := data.Len()
 maxDepth := 0
 for i := n; i > 0; i >>= 1 {
  maxDepth++
 }
 maxDepth *= 2
 quickSort(data, 0, n, maxDepth)
}
//Quick sort
//It will automatically choose whether to use heap sort or insert sort or quick sort. Quick sort is
func quickSort(data Interface, a, b, maxDepth int) {
 //Use hill insert if slice elements are less than 12
 for b-a > 12 { // Use ShellSort for slices <= 12 elements
  if maxDepth == 0 {
   HEAPSORT (data, a, b) // heap sort method, a = 0, B = n
   return
  }
  maxDepth--
  mlo, mhi := doPivot(data, a, b)
  // Avoiding recursion on the larger subproblem guarantees
  // a stack depth of at most lg(b-a).
  if mlo-a < b-mhi {
   quickSort(data, a, mlo, maxDepth)
   a = mhi // i.e., quickSort(data, mhi, b)
  } else {
   quickSort(data, mhi, b, maxDepth)
   b = mlo // i.e., quickSort(data, a, mlo)
  }
 }
 if b-a > 1 {
  // Do ShellSort pass with gap 6
  // It could be written in this simplified form cause b-a <= 12
  for i := a + 6; i < b; i++ {
   if data.Less(i, i-6) {
    data.Swap(i, i-6)
   }
  }
  insertionSort(data, a, b)
 }
}
// heap sort
func heapSort(data Interface, a, b int) {
 first := a
 lo := 0
 hi := b - a

 // Build heap with greatest element at top.
 //To build a heap structure, the top of the largest element is to build a big root heap
 for i := (hi - 1) / 2; i >= 0; i-- {
  siftDown(data, i, hi, first)
 }

 // Pop elements, largest first, into end of data.
 //Insert first to the end of data
 for i := hi - 1; i >= 0; i-- {
  Data. Swap (first, first + I) // data exchange
  Siftdown (data, lo, I, first) // heap re filtering
 }
}
// siftDown implements the heap property on data[lo, hi).
// first is an offset into the array where the root of the heap lies.
func siftDown(data Interface, lo, hi, first int) {
 //Hi is the length of the array
 //There is a way to take and save the following elements, but in order to make the method more abstract, this part is omitted, instead, swap with each other in swap
 Root: = Lo // subscript of root element
 for {
  Child: = 2 * root + 1 // subscript of left leaf node
  //Control for loop introduction, this writing method is more concise, you can see the heap sorting article I wrote
  if child >= hi { 
   break
  }
  //Prevent the array subscript from crossing the boundary, judge the left child and the right child
  if child+1 < hi && data.Less(first+child, first+child+1) { 
   child++
  }
  //Judge the relationship between the largest child and the root element
  if !data.Less(first+root, first+child) {
   return
  }
  //If all the above are met, data exchange will be carried out
  data.Swap(first+root, first+child)
  root = child
 }
}

There are many methods in this package. This package implements many methods, such as sorting inversion and binary search. The Quicksort () method is used to control whether the call is fast or heap.

summary

The above is the whole content of this article. I hope that the content of this article has a certain reference learning value for everyone’s study or work. If you have any questions, you can leave a message and exchange. Thank you for your support for developepaar.

Recommended Today

Notes on tensorflow 2 deep learning (I) tensorflow Foundation

This series of notes records the process of learning tensorflow2, mainly based on https://github.com/dragen1860/Deep-Learning-with-TensorFlow-book Learning First of all, it needs to be clear that tensorflow is a scientific computing library for deep learning algorithm, and the internal data is stored in theTensor objectAll operations (OPS) are also based on tensor objects. data type Fundamentals in […]