Go provides a built-in package called sort that you can use to sort arrays and slices. Here’s a simple example of how to sort an integer array in ascending order:
In this example, we use the sort.Ints() function to sort the numbers array in place. The function modifies the original array, so be aware that the order of elements in the numbers array will change after the sort.Ints() call.
If you want to sort an array of a different data type or in descending order, you can use the sort.Sort() function with a custom sort.Interface. Here’s an example of sorting a string array in descending order:
In this example, we define a custom type ByLength that implements the sort.Interface interface with the required methods (Len(), Less(), and Swap()). We then use sort.Sort(ByLength(names)) to sort the names array in descending order based on the length of the strings.
Remember that the sort the package works with slices, not arrays directly. If you have an actual array that you want to sort, you can use a slice to refer to the array elements, as shown in the examples.
Published At - Golang Program Example to Sort an Array
Comments
Post a Comment