Golang sort.IsSorted() Function with Examples

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

sort.IsSorted()

The IsSorted() function is an inbuilt function of the sort package which is used to check whether the given data (interface type) is sorted or not.

In Go language, an interface type can be defined as a set of method signatures. A value of interface type can store any value that implements those methods.

It accepts a parameter (data Interface) and returns true if data is sorted in ascending order; false, otherwise.

Syntax:

func IsSorted(data Interface) bool

Parameter(s):

  • data : An interface type which is to be checked.

Return Value:

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

Example:

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

package main

import (
	"fmt"
	"sort"
)

type Student struct {
	Name string
	Age  int
}

// ByAge implements sort.Interface for []Student
// based on the Age field.

type ByAge []Student

func (a ByAge) Len() int           { return len(a) }
func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }

func main() {
	Student1 := []Student{
		{"Amit", 21},
		{"Bobby", 19},
		{"Kartik", 23},
		{"Dolly", 24},
	}

	fmt.Println("Student1:", Student1)

	// Checking whether sorted by age or not
	if sort.IsSorted(ByAge(Student1)) == true {
		fmt.Println("Student1 is sorted based on the age.")
	} else {
		fmt.Println("Student1 is not sorted based on the age.")
	}
	fmt.Println()

	Student2 := []Student{
		{"Bobby", 19},
		{"Amit", 21},
		{"Kartik", 23},
		{"Dolly", 24},
	}

	fmt.Println("Student2:", Student2)

	// Checking whether sorted by age or not
	if sort.IsSorted(ByAge(Student2)) == true {
		fmt.Println("Student2 is sorted based on the age.")
	} else {
		fmt.Println("Student2 is not sorted based on the age.")
	}
}

Output:

Student1: [{Amit 21} {Bobby 19} {Kartik 23} {Dolly 24}]
Student1 is not sorted based on the age.

Student2: [{Bobby 19} {Amit 21} {Kartik 23} {Dolly 24}]
Student2 is sorted based on the age.

Golang sort Package »





Comments and Discussions!

Load comments ↻






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