7.6.6 searching and sorting slices and arrays
The standard library provides sort
packages for common search and sorting operations. You can use the sort
functions in the package func Ints(a []int)
to sort the tiles of type int. For example sort.Ints(arri)
, the variable Arri is an array or slice that needs to be sorted in ascending order. In order to check whether an array has been sorted, it can be checked by a function IntsAreSorted(a []int) bool
, and if it returns true, it is already sorted.
Similarly, you can use functions func Float64s(a []float64)
to sort float64 elements, or use functions to func Strings(a []string)
sort string elements.
To search for an element in an array or slice, the array or slice must first be sorted (because the standard library's search algorithm uses dichotomy). You can then use the function func SearchInts(a []int, n int) int
to search and return the index value of the corresponding result.
Of course, you can also search for float64 and strings:
searchfloat64s (A []intfunc searchstrings (A []string, x string) int
You can get more detailed information by viewing the official documentation.
This is how the sort
package is used, and we'll go into the details of it in section 11.6 and implement a version of our own.
Common operations for 7.6.7 slicing functions
The append we mentioned in section 7.5 is very useful, and it can be used in all aspects of operation:
After appending the elements of slice B to slice a:a = append(a, b...)
Copy the elements of slice A to the new slice B:
Make ([]Len (a))copy (b, a)
Delete the element at index i:a = append(a[:i], a[i+1:]...)
Remove the elements from the index i to J in slice a:a = append(a[:i], a[j:]...)
Extend the length of J Elements for slice A:a = append(a, make([]T, j)...)
Insert element X at the position of index I:a = append(a[:i], append([]T{x}, a[i:]...)...)
Insert a new slice of length J at index I:a = append(a[:i], append(make([]T, j), a[i:]...)...)
Insert all elements of slice B at the position of index I:a = append(a[:i], append(b, a[i:]...)...)
Remove the element x at the end of slice a:x, a = a[len(a)-1], a[:len(a)-1]
Append element x to slice a:a = append(a, x)
Therefore, you can use slices and append operations to represent any variable-length sequence.
From a mathematical point of view, a slice is equivalent to a vector and can be manipulated by defining a vector as a slice alias if necessary.
If you need a more complete solution, you can learn about several packages written by Eleanor McHugh: slices, chain, and lists.
Excerpt from: https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/07.6.md
Go language Notes-slicing functions common operations, adding and removing changes and searching, sorting