Posts

Golang Program Example to Sort an Array

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: package main import ( "fmt" "sort" ) func main () { // Sample unsorted integer array numbers := [] int { 5 , 2 , 9 , 1 , 5 , 6 } // Sorting the array in ascending order sort . Ints ( numbers ) // Display the sorted array fmt . Println ( "Sorted array:" , numbers ) } 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: package main import ( "fmt" "sort" ) t...
Recent posts