Searching Elements in an Array | Array Operations
Last Updated :
23 Jul, 2025
In this post, we will look into search operation in an Array, i.e., how to search an element in an Array, such as:
- Searching in an Unsorted Array using Linear Search
- Searching in a Sorted Array using Linear Search
- Searching in a Sorted Array using Binary Search
- Searching in an Sorted Array using Fibonacci Search
Searching operations in an Unsorted Array using Linear Search
In an unsorted array, the search operation can be performed by linear traversal from the first element to the last element, i.e. Linear Search

Coding implementation of the search operation:
C++
// C++ program to implement linear
// search in unsorted array
#include <bits/stdc++.h>
using namespace std;
// Function to implement search operation
int findElement(int arr[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;
// If the key is not found
return -1;
}
// Driver's Code
int main()
{
int arr[] = { 12, 34, 10, 6, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
// Using a last element as search element
int key = 40;
// Function call
int position = findElement(arr, n, key);
if (position == -1)
cout << "Element not found";
else
cout << "Element Found at Position: "
<< position + 1;
return 0;
}
// This code is contributed
// by Akanksha Rai
C
// C program to implement linear
// search in unsorted array
#include <stdio.h>
// Function to implement search operation
int findElement(int arr[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;
// If the key is not found
return -1;
}
// Driver's Code
int main()
{
int arr[] = { 12, 34, 10, 6, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
// Using a last element as search element
int key = 40;
// Function call
int position = findElement(arr, n, key);
if (position == -1)
printf("Element not found");
else
printf("Element Found at Position: %d",
position + 1);
return 0;
}
Java
// Java program to implement linear
// search in unsorted arrays
class Main {
// Function to implement
// search operation
static int findElement(int arr[], int n, int key)
{
for (int i = 0; i < n; i++)
if (arr[i] == key)
return i;
// If the key is not found
return -1;
}
// Driver's Code
public static void main(String args[])
{
int arr[] = { 12, 34, 10, 6, 40 };
int n = arr.length;
// Using a last element as search element
int key = 40;
// Function call
int position = findElement(arr, n, key);
if (position == -1)
System.out.println("Element not found");
else
System.out.println("Element Found at Position: "
+ (position + 1));
}
}
Python
# Python program for searching in
# unsorted array
def findElement(arr, n, key):
for i in range(n):
if (arr[i] == key):
return i
# If the key is not found
return -1
# Driver's code
if __name__ == '__main__':
arr = [12, 34, 10, 6, 40]
key = 40
n = len(arr)
# search operation
index = findElement(arr, n, key)
if index != -1:
print("Element Found at position: " + str(index + 1))
else:
print("Element not found")
# Thanks to Aditi Sharma for contributing
# this code
C#
// C# program to implement linear
// search in unsorted arrays
using System;
class main {
// Function to implement
// search operation
static int findElement(int[] arr, int n, int key)
{
for (int i = 0; i < n; i++)
if (arr[i] == key)
return i;
// If the key is not found
return -1;
}
// Driver Code
public static void Main()
{
int[] arr = { 12, 34, 10, 6, 40 };
int n = arr.Length;
// Using a last element as
// search element
int key = 40;
int position = findElement(arr, n, key);
if (position == -1)
Console.WriteLine("Element not found");
else
Console.WriteLine("Element Found at Position: "
+ (position + 1));
}
}
// This code is contributed by vt_m.
JavaScript
// Javascript program to implement linear
// search in unsorted array
// Function to implement search operation
function findElement( arr, n, key)
{
let i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;
return -1;
}
// Driver program
let arr = [12, 34, 10, 6, 40];
let n = arr.length;
// Using a last element as search element
let key = 40;
let position = findElement(arr, n, key);
if (position == - 1)
console.log("Element not found");
else
console.log("Element Found at Position: "
+ (position + 1));
PHP
<?php
// PHP program to implement linear
// search in unsorted array
// Function to implement
// search operation
function findElement($arr, $n, $key)
{
$i;
for ($i = 0; $i < $n; $i++)
if ($arr[$i] == $key)
return $i;
// If the key is not found
return -1;
}
// Driver Code
$arr = array(12, 34, 10, 6, 40);
$n = sizeof($arr);
// Using a last element
// as search element
$key = 40;
$position = findElement($arr, $n, $key);
if ($position == - 1)
echo("Element not found");
else
echo("Element Found at Position: " . ($position + 1));
// This code is contributed by Ajit.
?>
OutputElement Found at Position: 5
Time Complexity: O(N)
Auxiliary Space: O(1)
Searching in a Sorted Array using Linear Search
In a sorted array, the most trivial method for search operation is by using Linear Search.

Below is the implementation of the above approach:
C++
// C++ program to implement linear
// search in sorted array
#include <bits/stdc++.h>
using namespace std;
// Function to implement search operation
int findElement(int arr[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;
// If the key is not found
return -1;
}
// Driver's Code
int main()
{
int arr[] = { 5, 6, 7, 8, 9, 10 };
int n = sizeof(arr) / sizeof(arr[0]);
// Using a last element as search element
int key = 10;
// Function call
int position = findElement(arr, n, key);
if (position == -1)
cout << "Element not found";
else
cout << "Element Found at Position: "
<< position + 1;
return 0;
}
// This code is contributed
// by Akanksha Rai
C
// C program to implement linear
// search in sorted array
#include <stdio.h>
// Function to implement search operation
int findElement(int arr[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;
// If the key is not found
return -1;
}
// Driver's Code
int main()
{
int arr[] = { 5, 6, 7, 8, 9, 10 };
int n = sizeof(arr) / sizeof(arr[0]);
// Using a last element as search element
int key = 10;
// Function call
int position = findElement(arr, n, key);
if (position == -1)
printf("Element not found");
else
printf("Element Found at Position: %d",
position + 1);
return 0;
}
Java
// Java program to implement linear
// search in sorted arrays
class Main {
// Function to implement
// search operation
static int findElement(int arr[], int n, int key)
{
for (int i = 0; i < n; i++)
if (arr[i] == key)
return i;
// If the key is not found
return -1;
}
// Driver's Code
public static void main(String args[])
{
int arr[] = { 5, 6, 7, 8, 9, 10 };
int n = arr.length;
// Using a last element as search element
int key = 10;
// Function call
int position = findElement(arr, n, key);
if (position == -1)
System.out.println("Element not found");
else
System.out.println("Element Found at Position: "
+ (position + 1));
}
}
Python
# Python program for searching in
# sorted array
def findElement(arr, n, key):
for i in range(n):
if (arr[i] == key):
return i
# If the key is not found
return -1
# Driver's code
if __name__ == '__main__':
arr = [5, 6, 7, 8, 9, 10]
key = 10
n = len(arr)
# search operation
index = findElement(arr, n, key)
if index != -1:
print("Element Found at position: " + str(index + 1))
else:
print("Element not found")
# Thanks to Aditi Sharma for contributing
# this code
C#
// C# program to implement linear
// search in sorted arrays
using System;
class main {
// Function to implement
// search operation
static int findElement(int[] arr, int n, int key)
{
for (int i = 0; i < n; i++)
if (arr[i] == key)
return i;
// If the key is not found
return -1;
}
// Driver Code
public static void Main()
{
int[] arr = { 5, 6, 7, 8, 9, 10 };
int n = arr.Length;
// Using a last element as
// search element
int key = 10;
int position = findElement(arr, n, key);
if (position == -1)
Console.WriteLine("Element not found");
else
Console.WriteLine("Element Found at Position: "
+ (position + 1));
}
}
// This code is contributed by vt_m.
JavaScript
// Javascript program to implement linear
// search in sorted array
// Function to implement search operation
function findElement( arr, n, key)
{
let i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;
return -1;
}
// Driver program
let arr = [5, 6, 7, 8, 9, 10];
let n = arr.length;
// Using a last element as search element
let key = 10;
let position = findElement(arr, n, key);
if (position == - 1)
console.log("Element not found");
else
console.log("Element Found at Position: "
+ (position + 1));
PHP
<?php
// PHP program to implement linear
// search in sorted array
// Function to implement
// search operation
function findElement($arr, $n, $key)
{
$i;
for ($i = 0; $i < $n; $i++)
if ($arr[$i] == $key)
return $i;
// If the key is not found
return -1;
}
// Driver Code
$arr = array(5, 6, 7, 8, 9, 10);
$n = sizeof($arr);
// Using a last element
// as search element
$key = 10;
$position = findElement($arr, $n, $key);
if ($position == - 1)
echo("Element not found");
else
echo("Element Found at Position: " . ($position + 1));
// This code is contributed by Ajit.
?>
OutputElement Found at Position: 6
Time Complexity: O(N)
Auxiliary Space: O(1)
Searching in a Sorted Array using Binary Search
In a sorted array, the search operation can be performed efficiently by using binary search.

Below is the implementation of the above approach:
C++
// C++ program to implement binary search in sorted array
#include <bits/stdc++.h>
using namespace std;
int binarySearch(int arr[], int low, int high, int key)
{
if (high < low)
return -1;
int mid = (low + high) / 2; /*low + (high - low)/2;*/
if (key == arr[mid])
return mid;
if (key > arr[mid])
return binarySearch(arr, (mid + 1), high, key);
return binarySearch(arr, low, (mid - 1), key);
}
/* Driver code */
int main()
{
// Let us search 3 in below array
int arr[] = { 5, 6, 7, 8, 9, 10 };
int n, key;
n = sizeof(arr) / sizeof(arr[0]);
key = 10;
// Function call
cout << "Index: " << binarySearch(arr, 0, n - 1, key)
<< endl;
return 0;
}
// This code is contributed by NamrataSrivastava1
C
// C program to implement binary search in sorted array
#include <stdio.h>
int binarySearch(int arr[], int low, int high, int key)
{
if (high < low)
return -1;
int mid = (low + high) / 2; /*low + (high - low)/2;*/
if (key == arr[mid])
return mid;
if (key > arr[mid])
return binarySearch(arr, (mid + 1), high, key);
return binarySearch(arr, low, (mid - 1), key);
}
/* Driver Code */
int main()
{
// Let us search 3 in below array
int arr[] = { 5, 6, 7, 8, 9, 10 };
int n, key;
n = sizeof(arr) / sizeof(arr[0]);
key = 10;
// Function call
printf("Index: %d\n", binarySearch(arr, 0, n - 1, key));
return 0;
}
Java
// Java program to implement binary
// search in a sorted array
class Main {
// function to implement
// binary search
static int binarySearch(int arr[], int low, int high,
int key)
{
if (high < low)
return -1;
/*low + (high - low)/2;*/
int mid = (low + high) / 2;
if (key == arr[mid])
return mid;
if (key > arr[mid])
return binarySearch(arr, (mid + 1), high, key);
return binarySearch(arr, low, (mid - 1), key);
}
/* Driver Code*/
public static void main(String[] args)
{
int arr[] = { 5, 6, 7, 8, 9, 10 };
int n, key;
n = arr.length - 1;
key = 10;
// Function call
System.out.println("Index: "
+ binarySearch(arr, 0, n, key));
}
}
Python
# python 3 program to implement
# binary search in sorted array
def binary_search(arr, start, end, key):
# if case is evaluated when element is found else -1 is returned
if (start < end):
mid = (start + end) //2
if (key == arr[mid]):
return mid
if (key < arr[mid]):
return binary_search(arr, start, mid - 1, key)
if (key > arr[mid]):
return binary_search(arr, mid + 1, end, key)
else:
return -1
# Driver code
if __name__ == "__main__":
# Let us take a sorted array to find a key
arr = [5, 6, 7, 8, 9, 10]
key = 10
index = binary_search(arr, 0, len(arr) - 1, key)
if index != -1:
print(f"Element found at index {index}")
else:
print("Element not found")
# This code is contributed by Smitha Dinesh Semwal
# and improved by Rahul Varma
C#
// C# program to implement binary
// search in a sorted array
using System;
public class GFG {
// function to implement
// binary search
public static int binarySearch(int[] arr, int low,
int high, int key)
{
if (high < low) {
return -1;
}
int mid = (low + high) / 2;
if (key == arr[mid]) {
return mid;
}
if (key > arr[mid]) {
return binarySearch(arr, (mid + 1), high, key);
}
return binarySearch(arr, low, (mid - 1), key);
}
/* Driver Code */
public static void Main(string[] args)
{
int[] arr = new int[] { 5, 6, 7, 8, 9, 10 };
int n, key;
n = arr.Length;
key = 10;
// Function call
Console.WriteLine(
"Index: " + binarySearch(arr, 0, n - 1, key));
}
}
// This code is contributed by Shrikant13
JavaScript
// Javascript program to implement
// binary search in sorted array
function binarySearch( arr, low, high, key)
{
if (high < low)
return -1;
/*low + (high - low)/2;*/
let mid = Math.trunc((low + high) / 2);
if (key == arr[mid])
return mid;
if (key > arr[mid])
return binarySearch(arr, (mid + 1), high, key);
return binarySearch(arr, low, (mid - 1), key);
}
// Driver program
// Let us search 3 in below array
let arr = [ 5, 6, 7, 8, 9, 10 ];
let n, key;
n = arr.length;
key = 10;
console.log("Index: " + binarySearch(arr, 0, n - 1, key)
+ "</br>");
PHP
<?php
// PHP program to implement
// binary search in sorted array
function binarySearch($arr, $low,
$high, $key)
{
if ($high < $low)
return -1;
$mid = (int)($low + $high) / 2;
if ($key == $arr[(int)$mid])
return $mid;
if ($key > $arr[(int)$mid])
return binarySearch($arr, ($mid + 1),
$high, $key);
return (binarySearch($arr, $low,
($mid -1), $key));
}
// Driver Code
// Let us search 3 in below array
$arr = array(5, 6, 7, 8, 9, 10);
$n = count($arr);
$key = 10;
// Function call
echo "Index: ", (int)binarySearch($arr, 0,
$n-1, $key);
// This code is contributed by
// Srathore
?>
Time Complexity: O(log(n)) Using Binary Search
Auxiliary Space: O(log(n)) due to recursive calls, otherwise iterative version uses Auxiliary Space of O(1).
Searching in a Sorted Array using Fibonacci Search
Fibonacci Search is a comparison-based technique that uses Fibonacci numbers to search an element in a sorted array.

Below is the implementation of the above approach:
C++
// C++ program of the above approach
#include <iostream>
#include <vector>
using std::cout;
// Utility function to find minimum of two elements
int minimum(int x, int y) { return (x < y) ? x : y; }
/* Returns index of x if present, else returns -1 */
int fibonacciSearch(int arr[], int x, int n)
{
/* Initialize fibonacci numbers */
int fibMMm2 = 0; // (m-2)'th Fibonacci No.
int fibMMm1 = 1; // (m-1)'th Fibonacci No.
int fibM = fibMMm2 + fibMMm1; // m'th Fibonacci
/* fibM is going to store the smallest Fibonacci
Number greater than or equal to n */
while (fibM < n) {
fibMMm2 = fibMMm1;
fibMMm1 = fibM;
fibM = fibMMm2 + fibMMm1;
}
// Marks the eliminated range from front
int offset = -1;
/* while there are elements to be inspected. Note that
we compare arr[fibMm2] with x. When fibM becomes 1,
fibMm2 becomes 0 */
while (fibM > 1) {
// Check if fibMm2 is a valid location
int i = minimum(offset + fibMMm2, n - 1);
/* If x is greater than the value at index fibMm2,
cut the subarray array from offset to i */
if (arr[i] < x) {
fibM = fibMMm1;
fibMMm1 = fibMMm2;
fibMMm2 = fibM - fibMMm1;
offset = i;
}
/* If x is greater than the value at index fibMm2,
cut the subarray after i+1 */
else if (arr[i] > x) {
fibM = fibMMm2;
fibMMm1 = fibMMm1 - fibMMm2;
fibMMm2 = fibM - fibMMm1;
}
/* element found. return index */
else
return i;
}
/* comparing the last element with x */
if (fibMMm1 && arr[offset + 1] == x)
return offset + 1;
/*element not found. return -1 */
return -1;
}
// Driver Code
int main()
{
int arr[] = { 10, 22, 35, 40, 45, 50,
80, 82, 85, 90, 100, 235 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 235;
int ind = fibonacciSearch(arr, x, n);
if (ind >= 0)
cout << "Found at index: " << ind;
else
cout << x << " isn't present in the array";
return 0;
}
// This code is contributed by sourabh_jain.
C
// C program for Fibonacci Search
#include <stdio.h>
// Function to find minimum of two elements
int minimum(int x, int y) { return (x <= y) ? x : y; }
/* Returns index of x if present, else returns -1 */
int fibonacciSearch(int arr[], int x, int n)
{
/* Initialize Fibonacci numbers */
int fibMMm2 = 0; // (m-2)'th Fibonacci number
int fibMMm1 = 1; // (m-1)'th Fibonacci number
int fibM = fibMMm2 + fibMMm1; // m'th Fibonacci number
/* fibM is going to store the smallest Fibonacci
number greater than or equal to n */
while (fibM < n) {
fibMMm2 = fibMMm1;
fibMMm1 = fibM;
fibM = fibMMm2 + fibMMm1;
}
// Marks the eliminated range from front
int offset = -1;
/* while there are elements to be inspected. Note that
we compare arr[fibMm2] with x. When fibM becomes 1,
fibMm2 becomes 0 */
while (fibM > 1) {
// Check if fibMm2 is a valid location
int i = minimum(offset + fibMMm2, n - 1);
/* If x is greater than the value at index fibMm2,
cut the subarray array from offset to i */
if (arr[i] < x) {
fibM = fibMMm1;
fibMMm1 = fibMMm2;
fibMMm2 = fibM - fibMMm1;
offset = i;
}
/* If x is greater than the value at index fibMm2,
cut the subarray after i+1 */
else if (arr[i] > x) {
fibM = fibMMm2;
fibMMm1 = fibMMm1 - fibMMm2;
fibMMm2 = fibM - fibMMm1;
}
/* element found. return index */
else
return i;
}
/* comparing the last element with x */
if (fibMMm1 && arr[offset + 1] == x)
return offset + 1;
/* element not found. return -1 */
return -1;
}
/* driver function */
int main(void)
{
int arr[] = { 10, 22, 35, 40, 45, 50,
80, 82, 85, 90, 100, 235 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 235;
int index = fibonacciSearch(arr, x, n);
if (index >= 0)
printf("Element found at index: %d", index);
else
printf("%d is not present in the array", x);
return 0;
}
// This code is contributed by sourabh_jain.
Java
// Java program of the above approach
import java.util.*; // adding util packages
class FibonacciSearch {
// Function to find the minimum of two elements
public static int minimum(int x, int y)
{
return (x <= y) ? x : y;
}
/* Returns the index of x if present, else returns -1 */
public static int fibonacciSearch(int arr[], int x,
int n)
{
/* Initialize Fibonacci numbers */
int fibMMm2 = 0; // (m-2)'th Fibonacci number
int fibMMm1 = 1; // (m-1)'th Fibonacci number
int fibM
= fibMMm2 + fibMMm1; // m'th Fibonacci number
/* fibM is going to store the smallest Fibonacci
Number greater than or equal to n */
while (fibM < n) {
fibMMm2 = fibMMm1;
fibMMm1 = fibM;
fibM = fibMMm2 + fibMMm1;
}
// Marks the eliminated range from the front
int offset = -1;
/* While there are elements to be inspected.
Note that we compare arr[fibMm2] with x.
When fibM becomes 1, fibMm2 becomes 0 */
while (fibM > 1) {
// Check if fibMm2 is a valid location
int i = minimum(offset + fibMMm2, n - 1);
/* If x is greater than the value at index
fibMm2,
cut the subarray array from offset to i */
if (arr[i] < x) {
fibM = fibMMm1;
fibMMm1 = fibMMm2;
fibMMm2 = fibM - fibMMm1;
offset = i;
}
/* If x is less than the value at index fibMm2,
cut the subarray after i+1 */
else if (arr[i] > x) {
fibM = fibMMm2;
fibMMm1 = fibMMm1 - fibMMm2;
fibMMm2 = fibM - fibMMm1;
}
/* Element found. Return index */
else
return i;
}
/* Comparing the last element with x */
if (fibMMm1 == 1 && arr[n - 1] == x)
return n - 1;
/* Element not found. Return -1 */
return -1;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 10, 22, 35, 40, 45, 50,
80, 82, 85, 90, 100, 235 };
int n = 12;
int x = 235;
int index = fibonacciSearch(arr, x, n);
if (index >= 0)
System.out.print("Element found at index: "
+ index);
else
System.out.print(
x + " isn't present in the array");
}
}
// This code is contributed by sourabh_jain.
Python
# Pythin3 program of the above approach
def fibonacci_search(arr, x, n):
# Initialize Fibonacci numbers
fibMMm2 = 0 # (m-2)'th Fibonacci No.
fibMMm1 = 1 # (m-1)'th Fibonacci No.
fibM = fibMMm2 + fibMMm1 # m'th Fibonacci
# fibM is going to store the smallest
# Fibonacci Number greater than or equal to n
while fibM < n:
fibMMm2 = fibMMm1
fibMMm1 = fibM
fibM = fibMMm2 + fibMMm1
# Marks the eliminated range from the front
offset = -1
# while there are elements to be inspected.
# Note that we compare arr[fibMm2] with x.
# When fibM becomes 1, fibMm2 becomes 0
while fibM > 1:
# Check if fibMm2 is a valid location
i = min(offset + fibMMm2, n - 1)
# If x is greater than the value at
# index fibMm2, cut the subarray array
# from offset to i
if arr[i] < x:
fibM = fibMMm1
fibMMm1 = fibMMm2
fibMMm2 = fibM - fibMMm1
offset = i
# If x is less than the value at
# index fibMm2, cut the subarray
# after i+1
elif arr[i] > x:
fibM = fibMMm2
fibMMm1 = fibMMm1 - fibMMm2
fibMMm2 = fibM - fibMMm1
# element found. return index
else:
return i
# comparing the last element with x
if fibMMm1 and arr[n - 1] == x:
return n - 1
# element not found. return -1
return -1
# Driver Code
arr = [10, 22, 35, 40, 45, 50,
80, 82, 85, 90, 100, 235]
n = len(arr)
x = 235
index = fibonacci_search(arr, x, n)
if index >= 0:
print("Element found at index:", index)
else:
print(x, "isn't present in the array")
# This code is contributed by sourabh_jain.
C#
// C# program of the above approach
using System;
class GFG {
// Function to find the minimum of two elements
public static int Min(int x, int y)
{
return (x <= y) ? x : y;
}
/* Returns the index of x if present, else returns -1 */
public static int FibonacciSearch(int[] arr, int x,
int n)
{
/* Initialize Fibonacci numbers */
int fibMMm2 = 0; // (m-2)'th Fibonacci number
int fibMMm1 = 1; // (m-1)'th Fibonacci number
int fibM = fibMMm2 + fibMMm1; // m'th Fibonacci
/* fibM is going to store the smallest Fibonacci
Number greater than or equal to n */
while (fibM < n) {
fibMMm2 = fibMMm1;
fibMMm1 = fibM;
fibM = fibMMm2 + fibMMm1;
}
// Marks the eliminated range from the front
int offset = -1;
/* While there are elements to be inspected.
Note that we compare arr[fibMm2] with x.
When fibM becomes 1, fibMm2 becomes 0 */
while (fibM > 1) {
// Check if fibMm2 is a valid location
int i = Min(offset + fibMMm2, n - 1);
/* If x is greater than the value at
index fibMm2, cut the subarray array
from offset to i */
if (arr[i] < x) {
fibM = fibMMm1;
fibMMm1 = fibMMm2;
fibMMm2 = fibM - fibMMm1;
offset = i;
}
/* If x is less than the value at
index fibMm2, cut the subarray
after i+1 */
else if (arr[i] > x) {
fibM = fibMMm2;
fibMMm1 = fibMMm1 - fibMMm2;
fibMMm2 = fibM - fibMMm1;
}
/* Element found. Return index */
else
return i;
}
/* Comparing the last element with x */
if (fibMMm1 == 1 && arr[n - 1] == x)
return n - 1;
/* Element not found. Return -1 */
return -1;
}
// Driver code
public static void Main()
{
int[] arr = { 10, 22, 35, 40, 45, 50,
80, 82, 85, 90, 100, 235 };
int n = 12;
int x = 235;
int index = FibonacciSearch(arr, x, n);
if (index >= 0)
Console.Write("Element found at index: "
+ index);
else
Console.Write(x
+ " isn't present in the array");
}
}
// This code is contributed by sourabh_jain.
JavaScript
// JavaScript program of the above approach
/* Returns the index of x if present, else returns -1 */
function fibonacciSearch(arr, x, n) {
/* Initialize Fibonacci numbers */
let fibMMm2 = 0; // (m-2)'th Fibonacci No.
let fibMMm1 = 1; // (m-1)'th Fibonacci No.
let fibM = fibMMm2 + fibMMm1; // m'th Fibonacci
/* fibM is going to store the smallest Fibonacci
Number greater than or equal to n */
while (fibM < n) {
fibMMm2 = fibMMm1;
fibMMm1 = fibM;
fibM = fibMMm2 + fibMMm1;
}
// Marks the eliminated range from the front
let offset = -1;
/* While there are elements to be inspected.
Note that we compare arr[fibMm2] with x.
When fibM becomes 1, fibMm2 becomes 0 */
while (fibM > 1) {
// Check if fibMm2 is a valid location
let i = Math.min(offset + fibMMm2, n - 1);
/* If x is greater than the value at
index fibMm2, cut the subarray array
from offset to i */
if (arr[i] < x) {
fibM = fibMMm1;
fibMMm1 = fibMMm2;
fibMMm2 = fibM - fibMMm1;
offset = i;
}
/* If x is less than the value at index fibMm2,
cut the subarray after i+1 */
else if (arr[i] > x) {
fibM = fibMMm2;
fibMMm1 = fibMMm1 - fibMMm2;
fibMMm2 = fibM - fibMMm1;
}
/* Element found. Return index */
else return i;
}
/* Comparing the last element with x */
if (fibMMm1 && arr[n - 1] == x) {
return n - 1;
}
/* Element not found. Return -1 */
return -1;
}
/* Driver code */
let arr = [10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100, 235];
let n = arr.length;
let x = 235;
let index = fibonacciSearch(arr, x, n);
if (index >= 0) {
console.log("Element found at index: " + index);
} else {
console.log(x + " isn't present in the array");
}
// This code is contributed by sourabh_jain.
PHP
<?php
// PHP program of the above approach
/* Returns the index of x if present, else returns -1 */
function fibonacciSearch($arr, $x, $n)
{
/* Initialize Fibonacci numbers */
$fibMMm2 = 0; // (m-2)'th Fibonacci No.
$fibMMm1 = 1; // (m-1)'th Fibonacci No.
$fibM = $fibMMm2 + $fibMMm1; // m'th Fibonacci
/* fibM is going to store the smallest Fibonacci
Number greater than or equal to n */
while ($fibM < $n)
{
$fibMMm2 = $fibMMm1;
$fibMMm1 = $fibM;
$fibM = $fibMMm2 + $fibMMm1;
}
// Marks the eliminated range from the front
$offset = -1;
/* While there are elements to be inspected.
Note that we compare arr[fibMm2] with x.
When fibM becomes 1, fibMm2 becomes 0 */
while ($fibM > 1)
{
// Check if fibMm2 is a valid location
$i = min($offset + $fibMMm2, $n - 1);
/* If x is greater than the value at
index fibMm2, cut the subarray array
from offset to i */
if ($arr[$i] < $x)
{
$fibM = $fibMMm1;
$fibMMm1 = $fibMMm2;
$fibMMm2 = $fibM - $fibMMm1;
$offset = $i;
}
/* If x is less than the value at
index fibMm2, cut the subarray
after i+1 */
elseif ($arr[$i] > $x)
{
$fibM = $fibMMm2;
$fibMMm1 = $fibMMm1 - $fibMMm2;
$fibMMm2 = $fibM - $fibMMm1;
}
/* Element found. Return index */
else
return $i;
}
/* Comparing the last element with x */
if ($fibMMm1 == 1 && $arr[$n - 1] == $x)
return $n - 1;
/* Element not found. Return -1 */
return -1;
}
/* Driver code */
$arr = array(10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100, 235);
$n = count($arr);
$x = 235;
$index = fibonacciSearch($arr, $x, $n);
if ($index >= 0)
printf("Element found at index: " . $index);
else
printf($x . " isn't present in the array");
?>
// This code is contributed by sourabh_jain.
Time Complexity: O(log(n)) Using Fibonacci Search
Auxiliary Space: O(1) Using Fibonacci Search
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem