Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




GO - SORT ARRAY ELEMENTS


How to sort a String type Array in Ascending Order?


The 'sort.Strings()' Function is used to sort a String Array in Ascending order.


Example :



package main
import "fmt"
import "sort"
    
func main() {
    
    var arr = []string{"Mohan", "John", "Paul", "Kriti", "Salim"}
    sort.Strings(arr)	
    fmt.Println("The Sorted Array in ascending order is ",arr)			 	
}


Output :



 The Sorted Array in ascending order is [John Kriti Mohan Paul Salim]

So, in the above code we have created a 'Array' and initialised to the variable 'x'.


var arr = []string{"Mohan", "John", "Paul", "Kriti", "Salim"}

Below is how the values are positioned in the Array,


java_Collections

Now, to sort the String Array, Go provides us with a 'sort' package. So, to use the 'sort' package, we need to import it first.


import "sort"

Then we have used the 'Strings()' Function from the 'sort' package to sort the Array 'arr' in ascending order.


sort.Strings(arr)

And the Array 'arr' gets sorted with 'John' as the first value, 'Kriti' second and 'Mohan' as the third, 'Paul' as fourth and 'Salim' as the fifth value.


java_Collections

And we get the below output.


The Sorted Array in ascending order is [John Kriti Mohan Paul Salim]

How to sort a Array with numbers in Increasing Order?


Even here the 'sort' package to sort an integer Array with numbers in Increasing Order.


Example :



package main
import "fmt"
import "sort"
    
func main() {
    
    var arr = []int{5, 3, 2, 4}
    sort.Ints(arr)	
    fmt.Println("The Sorted Array in ascending order is ",arr)			 	
}


Output :



 The Sorted Array in ascending order is [2 3 4 5]

So, in the above code we have created an Integer 'Array' and initialised to the variable 'arr'.


var arr = []int{5, 3, 2, 4}

Below is how the values are positioned in the Array,


java_Collections

Then we have used the 'Ints()' Function from the 'sort' package to sort the Array 'x' in increasing order.


sort.Ints(arr)

And the numbers in the Array 'x' gets sorted.


java_Collections

And we get the below output.


The Sorted Array in ascending order is [2 3 4 5]