Question
Write a function that searches for an element in an array and returns its index. If the element is not found, return -1.
Approach
- Loop through the array from start to end.
- If the current element matches the search target, return its index.
- If no match is found by the end, return
-1.
Example
Input: arr = [2, 6, 4, 8, 1, 9], x = 2
Output: 0
Input: arr = [2, 6, 4, 8, 1, 9], x = 7
Output: -1
Time and Space Complexity
- Time Complexity: O(n), where n is the number of elements in the array.
- Space Complexity: O(1), as we are using constant extra space.
function searchElement(arr, x) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === x) {
return i;
}
}
return -1;
}
let arr = [2, 6, 4, 8, 1, 9];
let result = searchElement(arr, 2);
console.log("Result:", result); // Output: 0
#include <stdio.h>
int searchElement(int arr[], int n, int x) {
for (int i = 0; i < n; i++) {
if (arr[i] == x) return i;
}
return -1;
}
int main() {
int arr[] = {2, 6, 4, 8, 1, 9};
int result = searchElement(arr, 6, 2);
printf("Result: %d\n", result); // Output: 0
return 0;
}
#include <iostream>
using namespace std;
int searchElement(int arr[], int n, int x) {
for (int i = 0; i < n; i++) {
if (arr[i] == x) return i;
}
return -1;
}
int main() {
int arr[] = {2, 6, 4, 8, 1, 9};
int result = searchElement(arr, 6, 2);
cout << "Result: " << result << endl; // Output: 0
return 0;
}
public class Main {
public static int searchElement(int[] arr, int x) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == x) return i;
}
return -1;
}
public static void main(String[] args) {
int[] arr = {2, 6, 4, 8, 1, 9};
int result = searchElement(arr, 2);
System.out.println("Result: " + result); // Output: 0
}
}
def search_element(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
arr = [2, 6, 4, 8, 1, 9]
result = search_element(arr, 2)
print("Result:", result) # Output: 0
