×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang sort.IntsAreSorted() Function with Examples

Golang | sort.IntsAreSorted() Function: Here, we are going to learn about the IntsAreSorted() function of the sort package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 11, 2021

sort.IntsAreSorted()

The IntsAreSorted() function is an inbuilt function of the sort package which is used to check whether the given slice of Ints (int type of elements) is sorted in increasing order or not.

It accepts a parameter (x []int) and returns true if x is sorted in ascending order; false, otherwise.

Syntax

func IntsAreSorted(x []int) bool

Parameters

  • x : Slice of Ints is to be checked whether sorted or not.

Return Value

The return type of the IntsAreSorted() function is a bool, it returns true if the given slice of ints is sorted in ascending order; false, otherwise.

Example 1

// Golang program to demonstrate the
// example of sort.IntsAreSorted() Function

package main

import (
	"fmt"
	"sort"
)

func main() {
	x := []int{-123, 10, 20, 15, 0, -10}
	fmt.Println("x:", x)
	fmt.Println("sort.IntsAreSorted(x):",
		sort.IntsAreSorted(x))
	fmt.Println()

	x = []int{-65535, 0, 1, 2, 10, 255, 65535}
	fmt.Println("x:", x)
	fmt.Println("sort.IntsAreSorted(x):",
		sort.IntsAreSorted(x))
}

Output:

x: [-123 10 20 15 0 -10]
sort.IntsAreSorted(x): false

x: [-65535 0 1 2 10 255 65535]
sort.IntsAreSorted(x): true

Example 2

// Golang program to demonstrate the
// example of sort.IntsAreSorted() Function

package main

import (
	"fmt"
	"sort"
)

func main() {
	x := []int{108, 64, 0, -10, 9, 255}
	fmt.Println("x:", x)

	// Checking whether x is sorted or not,
	// if not sorted then sorting the x, and printing
	if sort.IntsAreSorted(x) == true {
		fmt.Println("Elements are already sorted")
	} else {
		fmt.Println("Elements are not sorted")
		fmt.Println("Sorting....")
		sort.Ints(x)
		fmt.Println("Sorting done.")
		fmt.Println("x:", x)
	}
	fmt.Println()

	x = []int{0, 10, 30, 40, 50}
	fmt.Println("x:", x)

	// Checking whether x is sorted or not,
	// if not sorted then sorting the x
	// and printing
	if sort.IntsAreSorted(x) == true {
		fmt.Println("Elements are already sorted")
	} else {
		fmt.Println("Elements are not sorted")
		fmt.Println("Sorting....")
		sort.Ints(x)
		fmt.Println("Sorting done.")
		fmt.Println("x:", x)
	}
}

Output:

x: [108 64 0 -10 9 255]
Elements are not sorted
Sorting....
Sorting done.
x: [-10 0 9 64 108 255]

x: [0 10 30 40 50]
Elements are already sorted

Golang sort Package »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.