Golang program to find the last occurrence of a target element in a sorted slice


In this article, we will learn how to write a golang program to find the last occurrence of a target element in a sorted slice using linear and binary search approach. We will use two programs in this article. In the first program we will use the Linear search approach while in the second one we will use the binary search approach to implement the result.

Using the Linear Search Approach

The simplest method to find the last occurrence of a target element in a sorted slice is to perform a linear search. In this method, we iterate through the slice from the end until we find the target element.

Algorithm

  • Step 1 − First, we need to import the fmt package.

  • Step 2 − Then create a function named lastIndexOfLinear() that accepts two arguments one is the array of integers and other is the number to be searched in the array.

  • Step 3 − Inside the function use a for loop to iterate through the slice from the end.

  • Step 4 − If the current element is equal to the target element, set "lastIndex" to the current index

  • Step 5 − Continue the iteration until the start of the slice is reached and return the lastIndex.

  • Step 6 − Now, start the main() function. Inside the main() initialize an array of integers and add values to them.

  • Step 7 − Further, store the element to be searched and pass it along with the array to the above created function.

  • Step 8 − Store the result in a variable and print it on the screen.

Example

The following Example demonstrates how to develop go language program to find the last occurrence of a target element in a sorted slice by using the linear search approach

package main

import (
   "fmt"
)

func lastIndexOfLinear(nums []int, target int) int {
   for i := len(nums) - 1; i >= 0; i-- {
      if nums[i] == target {
         return i
      }
   }
   return -1
}

func main() {
   nums := []int{10, 20, 30, 40, 50}
   fmt.Println("The given array is:", nums)
   var target int = 40
   fmt.Println("The element to be searched is:", target)
   res := lastIndexOfLinear(nums, target)
   fmt.Println("The given element", target, "is present in the position:", res)
}

Output

The given array is: [10 20 30 40 50]
The element to be searched is: 40
The given element 40 is present in the position: 3

Using Binary Search Approach

Binary search is a more efficient method to find the last occurrence of a target element in a sorted slice. In this method, we divide the slice into two halves and continue the search in the half that may contain the target element.

Algorithm

  • Step 1 − First, we need to import the fmt package.

  • Step 2 − Then create a function named lastIndexOfLinear() that accepts two arguments one is the array of integers and other is the number to be searched in the array.

  • Step 3 − Inside the function set "start" to 0 and "end" to the length of the slice – 1

  • Step 4 − While "start" is less than or equal to "end" Set "mid" to the average of "start" and "end"

  • Step 5 − If the element at index "mid" is equal to the target element Set "lastIndex" to "mid" and set "start" to "mid + 1"

  • Step 6 − Else if the element at index "mid" is greater than the target element, set "end" to "mid - 1"

  • Step 7 − Else, set "start" to "mid + 1" and return the "lastIndex" variable.

  • Step 8 − Now, start the main() function and initialize the array of integers along with the element to be searched.

  • Step 9 − Now, call the function created above by passing required arguments to it and store the result in a variable.

Example

In the following Example we will understand how to develop go language program to find the last occurrence of a target elemtnt in a sorted slice by using binary search approach

package main

import (
   "fmt"
)

func binarySearchLastOccurrence(slice []int, target int) int {
   start := 0
   end := len(slice) - 1
   lastIndex := -1
   for start <= end {
      mid := (start + end) / 2
      if slice[mid] == target {
         lastIndex = mid
         start = mid + 1
      } else if slice[mid] > target {
         end = mid - 1
      } else {
         start = mid + 1
      }
   }
   return lastIndex
}

func main() {
   nums := []int{10, 2, 5, 40, 7}
   fmt.Println("The given array is:", nums)
   var target int = 5
   fmt.Println("The element to be searched is:", target)
   res := binarySearchLastOccurrence(nums, target)
   fmt.Println("The given element", target, "is present in the position:", res)
}

Output

The given array is: [10 2 5 40 7]
The element to be searched is: 5
The given element 5 is present in the position: 2

Using Standard Library Function

Go provides a standard library function called sort.SearchInts that can be used to find the last occurrence of a target element in a sorted slice. This function uses binary search internally and returns the index of the first element that is greater than or equal to the target element.

Algorithm

  • First, we need to import the fmt and sort packages.

  • Then create the function named lastIndexOfStandard() and call the sort.SearchInts function with the sorted slice nums and the target element target

  • If the returned index i is greater than 0 and nums[i-1] is equal to the target element, return i – 1. Otherwise, return -1.

  • Now, call the main() function. Inside the main() initialize the array along with the element to be searched.

Example

In the following Example we will understand how to develop go language program to find the last occurrence of a target element by using standard library function

package main

import (
   "fmt"
   "sort"
)

func lastIndexOfStandard(nums []int, target int) int {
   i := sort.SearchInts(nums, target)
   if i >= 0 && nums[i] == target {
      return i
   } else {
      return -1
   }

}

func main() {
   nums := []int{10, 20, 30, 40, 50}
   fmt.Println("The given array is:", nums)
   var target int = 40
   fmt.Println("The element to be searched is:", target)
   res := lastIndexOfStandard(nums, target)
   fmt.Println("The given element", target, "is present in the position:", res)
}

Output

The given array is: [10 20 30 40 50]
The element to be searched is: 40
The given element 40 is present in the position: 3

Conclusion

In this article, we discussed three different methods to solve this problem in Golang. The linear search method is the simplest but least efficient, while the binary search and binary search with recursion methods are more efficient but slightly more complex. You can choose the method that suits your use case based on the size of the slice and the expected frequency of target element occurrences.

Updated on: 05-Apr-2023

100 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements