Golang in the Sort package usage

Source: Internet
Author: User
Tags sorts
This is a creation in Article, where the information may have evolved or changed.

The Golang also implements the packet sort package for the sorting algorithm.

There are 3 basic sorting algorithms implemented in the sort package: insert sort. Fast and heap sorting. As in other languages, these three methods are not public, they are used only within the sort package. So the user does not have to think about the sort order when using the sort package, sort. Interface defines three methods: Get the Len () method for the length of the data set, compare the less () method with two element sizes, and swap () methods that exchange two element locations to sort the data collection smoothly. the sort package automatically chooses an efficient sorting algorithm based on the actual data .


Type Interface

Type Interface Interface {    len () int    //Len is the total number of elements in the set less      (i, J int) BOOL// Returns true if the element of index i is less than the element with index J, otherwise false   swap (i, J int)  //Swap index is an element of I and J }

Any implementation of sort. The type of Interface, which is typically a collection, can be sorted using the methods in the package. These methods require that the index of the listed element in the collection be an integer.


Func float64s (A []float64)//float64s sorts slice A of type float64 in ascending order
Func float64saresorted (A []float64) bool//Determines if the sort func Ints (a []int) has been sorted]

Func Ints (A []int)//ints arranges int slices in ascending order.
The Func intsaresorted (a []int) bool//intsaresorted determines whether an int slice has been sorted in ascending order.
The Func issorted (data Interface) bool issorted Determines whether the data is sorted. Includes a variety of data types that can be sort-judged.

Func Strings (A []string)//strings arranges string slices in ascending order.
Func stringsaresorted (A []string) bool//stringsaresorted determines whether a string slice has been sorted in ascending order.

Package Mainimport ("FMT" "sort")//define interface{} and implement sort.  Three methods of the interface interface type Intslice []intfunc (c intslice) len () int {return Len (c)}func (c intslice) Swap (i, J int) {C[i], c[j] = C[j], C[i]}func (c intslice) Less (i, J int) bool {return C[I] < C[j]}func main () {A: = Intslice{1, 3, 5, 7, 2}b: = [ ]float64{1.1, 2.3, 5.3, 3.4}c: = []int{1, 3, 5, 4, 2}fmt. Println (sort. IsSorted (a))//falseif!sort. IsSorted (a) {sort. Sort (a)}if!sort. Float64saresorted (b) {sort. float64s (b)}if!sort. Intsaresorted (c) {sort. Ints (c)}fmt. Println (a)//[1 2 3 5 7]fmt. Println (b)//[1.1 2.3 3.4 5.3]fmt. PRINTLN (c)//[1 2 3 4 5]}

Func Search (n int, f func (int) bool) int

Search uses dichotomy to find, and the search () method uses a "binary lookup" algorithm that searches for a specified slice [0:n] and returns the smallest I (0<=i<n) value that can make F (i) =true, and it assumes that f (i) =true, if F (i+ 1) =true, that is, for slices [0:n],i before the slice element will cause the F () function to return the elements after false,i and I will cause the F () function to return True. However, theSearch () method returns n(instead of 1) when I cannot be found in the slice (at which point the slice element does not return the F () function to True) when F (i) =true i.

Search is often used to look for a value x, such as an array or a slice, indexed to I in a sorted, indexable data structure. In this case, the argument F, which is typically a closure, captures the value to be searched and how the data structure is indexed and sorted.

In order to find a value instead of a range of values, if slice is sorted in ascending order, then >= should be used in F func, and <= should be used if slice is sorted in descending order. Examples are as follows: Package main

Package Mainimport ("FMT" "sort") Func main () {a: = []int{1, 2, 3, 4, 5}b: = sort. Search (Len (a), func (i int) bool {return a[i] >=) fmt. Println (b)//5, not found, returns the length of a slice 5 instead of -1c: = sort. Search (Len (a), func (i int) bool {return a[i] <= 3}) fmt. Println (c)                             //0, using the binary method to find, returns the index of the leftmost value that matches the condition, which is 0d: = sort. Search (Len (a), func (i int) bool {return A[i] = = 3}) fmt. Println (d)                          //2}

Interesting examples on official web:

Func guessinggame () {var s stringfmt. Printf ("Pick an integer from 0 to 100.\n") Answer: = sort. Search (func (i int) bool {FMT. Printf ("Is your number <=%d?", i) fmt. SCANF ("%s", &s) return s! = "" && s[0] = = ' y '}) fmt. Printf ("Your number is%d.\n", answer)}

Func searchfloat64s (A []float64, x float64) int//searchfloat64s searches for x in the float64s slice and returns the index as described in the search function. Returns the index position where the x value can be inserted, and if x does not exist, the length of the returned array a slice must be in ascending order
Func searchints (A []int, x int) int//searchints searches the ints slice for x and returns the index as described in the search function. Returns the index position where the x value can be inserted, and if x does not exist, the length of the returned array a slice must be in ascending order
Func searchstrings (A []string, x String) int//searchfloat64s searches the strings slice for x and returns the index as described in the search function. Returns the index position where the x value can be inserted, and if x does not exist, the length of the returned array a slice must be in ascending order

It should be noted that the above three search search methods, the corresponding slice must be sorted in ascending order, otherwise there will be strange results.

Package Mainimport ("FMT" "sort") Func main () {a: = []string{"A", "C"}i: = sort. Searchstrings (A, "B") fmt. Println (i)//1b: = []string{"A", "B", "C", "D"}i = sort. Searchstrings (b, "B") fmt. Println (i)//1c: = []string{"D", "C"}i = sort. Searchstrings (c, "B") fmt. Println (i)//0d: = []string{"C", "D", "B"}i = sort. Searchstrings (D, "B") fmt. PRINTLN (i)//0, because D is not arranged in ascending order, there are strange results, which can be explained according to the definition of searchstrings. See below. }func Searchstrings (A []string, x string) int {return Search (Len (a), func (i int) bool {return a[i] >= x})}
Thus, for exact lookups, []string] must be sorted in ascending order.

The Func sort (data Interface)//sort the data. It invokes data once. Len to determine the length of the sort n, call data. Less and data. The cost of Swap is O (N*log (n)). This sort is an unstable sort. He decided to use different sorting methods (insert sort, heap sort, quick row) depending on the form

The Func Stable (data Interface) Stable sorts the data, but if there are equal elements in data in the sequence, their original order will not change, i.e. if there are two equal element num, their initial index is I and J, respectively. And I<j, after using stable to sort data, I is still less than J. Sorting by using sort directly does not guarantee this point.

There are three types of interface implemented by Golang itself, Float64slice,intslice,stringslice, as follows:

Type Float64slice

Type Float64slice []float64
Float64slice methods for implementing interfaces for []float6, in ascending order.

Func (P float64slice) Len () int//Seek length func (P float64slice) Less (i, J int) bool//ratio size func (P float64slice) Search (x Floa T64) int//Find Func (P float64slice) sort ()//Sort func (P float64slice) Swap (i, J int)//swap position



Type Intslice

Type Intslice []int

Intslice methods for implementing interfaces for []int, in ascending order.

Func (P intslice) Len () IntFunc (P intslice) Less (i, J int) Boolfunc (P intslice) Search (x int) IntFunc (P intslice) Sort ( ) func (P intslice) Swap (i, J int)


Type Stringslice

Type Stringslice []string

Stringslice methods for implementing interfaces for []string, in ascending order.

Func (P stringslice) Len () IntFunc (P stringslice) Less (i, J int) Boolfunc (P stringslice) Search (x String) IntFunc (P Str Ingslice) Sort () func (P stringslice) Swap (i, J int)


Func Reverse (data Interface) Interface

Func Reverse (data Interface) Interface
Reverse the reverse order of data

Package Mainimport ("FMT" "sort") Func main () {a: = []int{1, 2, 5, 3, 4}fmt. Println (a)        //[1 2 5 3 4]sort. Sort (sort. Reverse (sort. Intslice (a))) Fmt. Println (a)        //[5 4 3 2 1]}





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.