- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write a Golang program to search an element in a sorted array
Approach to solve this problem
- Step 1: Iterate the array from the 0th index to n-1, where n is the size of the given array.
- Step 2: Declare low=0th index and high=n-1. Start a for loop till low is lesser than high.
- Step 3: Find mid=(low+high)/2, if the element at the middle is equal to key, then return mid index.
- Step 4: If the element at mid is greater than the key, then make high = mid.
- Step 5: If the element at mid is lesser than the key, then make low = mid + 1.
- Step 6: If key is not present in the given array, then return -1.
Time Complexity: log2(n)
Program
package main import "fmt" func binarySearch(arr []int, key int) int{ high := len(arr) - 1 low := 0 var mid int for low <= high { mid = (high+low)/2 if arr[mid] == key { return mid } else if arr[mid] > key { high = mid } else { low = mid + 1 } } return -1 } func main(){ fmt.Println(binarySearch([]int{1, 4, 6, 8, 9, 10}, 11)) fmt.Println(binarySearch([]int{1, 4, 6, 8, 9, 10}, 8)) fmt.Println(binarySearch([]int{1, 4, 6, 8, 9, 10}, 10)) }
Output
-1 3 5
- Related Articles
- Write a Golang program to search an element in an array
- C++ program to search an element in a sorted rotated array
- Write a Golang program to find the frequency of an element in an array
- Write a Golang program to reverse an array
- Write a Golang program to find the frequency of each element in an array
- Golang program to search an element in the slice
- Write a Golang program to find the element with the minimum value in an array
- Swift Program to Search an Element in an Array
- Golang program to fill an array with a specific element
- Golang Program to search an item into the array using interpolation search
- Write a Golang program to sort an array using Bubble Sort
- Golang Program To Append An Element Into An Array
- Recursive program to linearly search an element in a given array in C++
- Write a Golang program to check whether a given array is sorted or not (Using Bubble Sort Technique)
- Java Program to Recursively Linearly Search an Element in an Array

Advertisements