Golang sort.Float64sAreSorted() Function with Examples

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

sort.Float64sAreSorted()

The Float64sAreSorted() function is an inbuilt function of the sort package which is used to check whether the given slice of float64s (float64 type of elements) is sorted in increasing order or not, with NaN values before any other values.

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

Syntax:

func Float64sAreSorted(x []float64) bool

Parameter(s):

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

Return Value:

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

Example 1:

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

package main

import (
	"fmt"
	"math"
	"sort"
)

func main() {
	x := []float64{1.2, 8.9, 12.50, -10.0, 20.0, 15.5}
	fmt.Println("x:", x)
	fmt.Println("sort.Float64sAreSorted(x):",
		sort.Float64sAreSorted(x))
	fmt.Println()

	x = []float64{math.NaN(), math.Inf(-1), 0, 1.2, 8.9, math.Inf(1)}
	fmt.Println("x:", x)
	fmt.Println("sort.Float64sAreSorted(x):",
		sort.Float64sAreSorted(x))
}

Output:

x: [1.2 8.9 12.5 -10 20 15.5]
sort.Float64sAreSorted(x): false

x: [NaN -Inf 0 1.2 8.9 +Inf]
sort.Float64sAreSorted(x): true

Example 2:

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

package main

import (
	"fmt"
	"math"
	"sort"
)

func main() {
	x := []float64{math.NaN(), math.Inf(-1), 0, 1.2, 8.9, math.Inf(1)}
	fmt.Println("x:", x)

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

	x = []float64{1.2, 8.9, 12.50, -10.0, 20.0, 15.5}
	fmt.Println("x:", x)

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

Output:

x: [NaN -Inf 0 1.2 8.9 +Inf]
Elements are already sorted

x: [1.2 8.9 12.5 -10 20 15.5]
Elements are not sorted
Sorting....
Sorting done.
x: [-10 1.2 8.9 12.5 15.5 20]

Golang sort Package »





Comments and Discussions!

Load comments ↻






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