Saturday 4 September 2021

Go Sorting

 Go has sort package which can be used for sorting the built-in as well as user defined data types.

The sort package has different methods to sort different data types like Ints(), Float64s(), Strings() etc.

We can check if the values are sort or not by using the AreSorted() methods like Float64sAreSorted(), IntsAreSorted() etc.

Go Sort Example

  1. package main  
  2. import (  
  3.     "sort"  
  4.     "fmt"  
  5. )  
  6. func main() {  
  7.   
  8.     intValue := []int{102058}  
  9.     sort.Ints(intValue)  
  10.     fmt.Println("Ints:   ", intValue)  
  11.   
  12.     floatValue := []float64{10.520.55.58.5}  
  13.     sort.Float64s(floatValue)  
  14.     fmt.Println("floatValue:   ", floatValue)  
  15.   
  16.     stringValue := []string{"Raj""Mohan""Roy"}  
  17.     sort.Strings(stringValue)  
  18.     fmt.Println("Strings:", stringValue)  
  19.   
  20.     str := sort.Float64sAreSorted(floatValue)  
  21.     fmt.Println("Sorted: ", str)  
  22. }  

Output:

Ints:    [5 8 10 20]
floatValue:    [5.5 8.5 10.5 20.5]
Strings: [Mohan Raj Roy]
Sorted:  true

We can also implement our own sorting schema, suppose we want to sort an array of string according to its length. In order to do that we have to implement our own Less, Len and Swap methods defined in the sort Interface.

Then we have to cast our array into the implemented type.

  1. package main  
  2. import "sort"  
  3. import "fmt"  
  4.   
  5. type  OrderByLengthDesc []string  
  6. func (s OrderByLengthDesc) Len() int {  
  7.     return len(s)  
  8. }  
  9. func (str OrderByLengthDesc) Swap(i, j int) {  
  10.     str[i], str[j] = str[j], str[i]  
  11. }  
  12. func (s OrderByLengthDesc) Less(i, j int) bool {  
  13.     return len(s[i]) > len(s[j])  
  14. }  
  15. func main() {  
  16.     city := []string{"Darbhanga""Bihar","Pachrukhi","Delhi"}  
  17.     sort.Sort(OrderByLengthDesc(city))  
  18.     fmt.Println(city)  
  19. }  

Output:

[Pachrukhi Darbhanga Bihar Delhi]


No comments:

Post a Comment