golang

Golang Sort Slice Examples

Sorting is a foundational programming operation that includes putting the elements in a particular order. The sort package, in which Go’s official library makes available, includes several functions to quickly sort the slices. Sorting slices is a common task in many applications, from organizing the data for presentation to optimizing the search algorithms. This article explores the different sorting techniques and demonstrates their usage in Go using the sort package.

Example 1: Golang Sort Slice in Ascending Order

The “sort.Slice()” function is the foremost function in Go that rearranges the elements of the slice in ascending order or descending order. Take into account the following illustration where the slice is arranged in ascending order:

package main
import (
   "fmt"
   "sort"
)
func main() {
   evenSlice := []int{10, 2, 8, 4, 0, 6}
   fmt.Println("Unsorted slice:", evenSlice)
  sort.Slice(evenSlice, func(i, j int) bool {
      return evenSlice[i] < evenSlice[j]
   })
   fmt.Println("Sorted slice:", evenSlice)
}

At the beginning of the main() function, we define the evenSlice slice with the {10, 2, 8, 4, 0, 6} values. This slice represents a collection of even numbers that are initially unsorted. To sort the evenSlice slice, the sort.Slice() function is employed with the slice. Inside the sort.Slice() function, a sorting function is provided as an argument. This function determines the sorting order by comparing the slice's two elements at “i” and “j” indices. If evenSlice[i] is less than evenSlice[j], it returns true; otherwise, it returns false. The sort.Slice() function uses this comparison function to rearrange the elements of the “evenSlice” slice in ascending order.

The results of the sorted slice in ascending order are generated in the following output screen:

Example 2: Golang Sort Part Slice

Next, the sorting is applied to the sub-slice of the specified slice in ascending order using the sort.Slice() function in Go.

package main
import (
    "fmt"
    "sort"
)
func main() {
    n := []int{9, 7, 3, 5}
    start := 0
    end := 3
    sort.Slice(n[start:end], func(i, j int) bool {
        return n[start+i] < n[start+j]
    })
    fmt.Println(n)
}

Initially, we create the “n” slice with the [9, 7, 3, 5] values. Additionally, two variables, “start” and “end”, are set to 0 and 3, respectively. These variables define the range of indices in the “n” slice that will be sorted. The “sort.Slice()” function is then called with the sub-slice “n[start:end]” as the first argument. This sub-slice contains the elements of “n” within the specified range. After that, a sorting function is given as the second argument inside the sort.Slice() function.

Here, that function receives two indices, “i" and “j”, which represent the elements within the sub-slice. To compare the elements within the sub-slice, the sorting function accesses the corresponding elements in the original slice using the start offset. It compares the n[start+i] and n[start+j]. Next, the sort.Slice() function uses the provided sorting function to rearrange the elements within the sub-slice in ascending order.

The following output displays that the elements within the specified range (start to end-1) are sorted, and the elements outside the range remain unchanged:

Example 3: Golang Sort Integer Slice Using the Sort.Ints() Function

Moreover, the most convenient to sort the slices of integers is the sort.Ints() function without the need for implementing the custom sorting methods. It acts directly on integer slices and performs an in-place sorting. The following program sorts the specified integers:

package main
import (
   "fmt"
   "sort"
)
func main() {
   IntSlice := []int{10, 13, 15, 11, 14, 12}
   fmt.Println("Unsorted slice:", IntSlice)
   sort.Ints(IntSlice)
   fmt.Println("Sorted slice:", IntSlice)
}

First, we declare and initialize the “IntSlice” slice with the [10, 13, 15, 11, 14, 12] values which represent a collection of integers that are initially unsorted. Then, the sort.Ints() function is called with the “IntSlice” slice as an argument to sort the “IntSlice”. The sort.Ints() function in this case internally sorts every part of the slice according to an optimized sorting algorithm. It modifies the original slice directly, rearranging its elements into a sorted order.

The following output first shows that the unsorted slice is displayed first, followed by the sorted slice:

Example 4: Golang Sort String Slice

Go also offers the sort.Strings() function of the sort package which is used to sort a slice of strings in a specific order. Here, the following program assists to sort the slice of strings:

package main
import (
    "fmt"
    "sort"
)
func main() {
    strSl := []string{"golang", "python", "java", "perl", "typescript"}
    sort.Strings(strSl)
    fmt.Println(strSl)
}

We first established the “strSl” slice with the [“golang”, “python”, “java”, “perl”, “typescript”] values which are not sorted. After that, we sort the “strSl” slice with the sort.Strings() function which sorts the elements of the slice in lexicographic order. This function modifies the original slice directly, rearranging its elements into sorted order based on their ASCII values.

The output sorts the string slice in ascending manner as displayed in the following:

Example 5: Golang Check Sort Slice Using the IntAreSort() Function

However, with the sort.IntsAreSorted() function of Go, we can check whether a given slice of integers is sorted in ascending order or not. Consider the following example program of the IntAreSort() function for the given slice:

package main
import (
    "fmt"
    "sort"
)
func main() {
    sl := []int{-33, 105, -42, 59, 18, 0, -3}
    fmt.Println("Slices:")
    fmt.Println("Unsorted Slice: ", sl)
    result := sort.IntsAreSorted(sl)
    fmt.Println("\nResult:")
    fmt.Println("Is given Slice sorted?: ", result)
}

First, an unsorted slice of random integers is defined as “sl”. This slice contains a collection of integers in no particular order. Next, we call the sort.IntsAreSorted() function and pass the “sl” slice as an argument. This function provides a Boolean result that indicates whether or not the slice input is arranged in ascending order. Then, the fmt.Println() function prints the results which outputs whether the given slice is sorted or not based on the returned Boolean value.

The output displays false for the sorting order of a slice of integers as it’s unsorted:

Example 6: Golang Reverse Sort Slice

Further, using the sortReverse() and sortStringSlice() functions from the sort package in Go, we can reverse-sort a slice of strings. The following program demonstrates the working of the sort.Reverse() function:

package main
import (
    "fmt"
    "sort"
)
func main() {
    vowelSlice := []string{"e", "a", "i", "u", "o"}
    fmt.Println("Before sorting :", vowelSlice)
    sort.Sort(sort.Reverse(sort.StringSlice(vowelSlice)))
    fmt.Println("After  sorting :", vowelSlice)
}

We begin by defining a slice of the “vowelSlice” string that contains the vowels “e”, “a”, “i”, “u”, and “o”. The initial content of the specified slice of strings is printed first using the “print” function. Next, the sorting operation is performed using the sort.Sort() function with the sort.Reverse() and sort.StringSlice() functions as arguments. Here, the “sort.Reverse()” creates a new type that reverses the order of the elements. It takes the “sort.StringSlice” type as its argument which converts the vowelSlice into a sortable type.

The output here displays the vowels in reverse alphabetical order:

Conclusion

We delved into various sorting functions with examples that sort the provided slice. We also covered about the sorting of sub-slices and checking if a slice is already sorted. Hence, we can leverage the sort package’s capabilities to tackle a wide range of sorting challenges in their Go projects.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content