×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang sort.Search() Function with Examples

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

sort.Search()

The Search() function is an inbuilt function of the sort package which is used to search the element and return the smallest index i in [0, n) at which f(i) is true. The Search() function uses binary search to search an element.

It accepts two parameters (n int, f func(int) bool) – n is the length of the list and f is a bool function that is used for the comparison and returns the smallest index.

Syntax

func Search(n int, f func(int) bool) int

Parameters

  • n : Length of the list.
  • f : Boolean function to be checked with each element of the list.

Return Value

The return type of the Search() function is an int, it returns the smallest index.

Example 1

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

// Searching a list sorted in ascending order

package main

import (
	"fmt"
	"sort"
)

func main() {
	x := []int{10, 20, 30, 40, 50}

	// Element to search
	v := 30

	ind := sort.Search(len(x), func(ind int) bool { return x[ind] >= v })
	if ind < len(x) && x[ind] == v {
		fmt.Printf("found %d at ind %d in %v\n", v, ind, x)
	} else {
		fmt.Printf("%d not found in %v\n", v, x)
	}

	// Element to search
	v = 60

	ind = sort.Search(len(x), func(ind int) bool { return x[ind] >= v })
	if ind < len(x) && x[ind] == v {
		fmt.Printf("found %d at ind %d in %v\n", v, ind, x)
	} else {
		fmt.Printf("%d not found in %v\n", v, x)
	}
}

Output:

found 30 at ind 2 in [10 20 30 40 50]
60 not found in [10 20 30 40 50]

Example 2

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

// Searching a list sorted in descending order

package main

import (
	"fmt"
	"sort"
)

func main() {
	x := []int{50, 40, 30, 20, 10}

	// Element to search
	v := 30

	ind := sort.Search(len(x), func(ind int) bool { return x[ind] <= v })
	if ind < len(x) && x[ind] == v {
		fmt.Printf("found %d at ind %d in %v\n", v, ind, x)
	} else {
		fmt.Printf("%d not found in %v\n", v, x)
	}

	// Element to search
	v = 60

	ind = sort.Search(len(x), func(ind int) bool { return x[ind] <= v })
	if ind < len(x) && x[ind] == v {
		fmt.Printf("found %d at ind %d in %v\n", v, ind, x)
	} else {
		fmt.Printf("%d not found in %v\n", v, x)
	}
}

Output:

found 30 at ind 2 in [50 40 30 20 10]
60 not found in [50 40 30 20 10]

Golang sort Package »




Comments and Discussions!

Load comments ↻





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