How to check if a slice is sorted in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "sort"
)

func main() {
    numbers := []int{1, 2, 3, 4, 5}

    isSorted := sort.SliceIsSorted(numbers, func(i, j int) bool {
        return numbers[i] < numbers[j]
    })

    fmt.Println("Is the slice sorted?", isSorted)
}

 
 
 
/*
run:
 
Is the slice sorted? true
 
*/

 



answered Sep 16, 2025 by avibootz
...