Anugreh Raina
0
Q:

linear search in c++

let arr = [1, 3, 5, 7, 8, 9];
let binarySearch = (arr, x , strt, end) => {
  if(end < strt) return false;
  let mid = Math.floor((strt + end) / 2);
  if(arr[mid] === x) {
    return true;
  }
  if(arr[mid] < x) {
    return binarySearch(arr, x, mid+1, end);
  }
  if(arr[mid] > x) {
    return binarySearch(arr, x , strt, mid-1);
  }
}

let strt = 0, end = arr.length -1;
let bool = binarySearch(arr, 7, strt, end);
console.log(bool);
3
// C code to linearly search x in arr[]. If x 
// is present then return its location, otherwise 
// return -1 
  
#include <stdio.h> 
  
int search(int arr[], int n, int x) 
{ 
    int i; 
    for (i = 0; i < n; i++) 
        if (arr[i] == x) 
            return i; 
    return -1; 
} 
  
int main(void) 
{ 
    int arr[] = { 2, 3, 4, 10, 40 }; 
    int x = 10; 
    int n = sizeof(arr) / sizeof(arr[0]); 
    int result = search(arr, n, x); 
    (result == -1) ? printf("Element is not present in array") 
                   : printf("Element is present at index %d", 
                            result); 
    return 0; 
}
1
bool linearsearch(int A[], int N, int X) {
  for (int i=0; i<N; i++) 
    if (A[i] == X) return true;
  return false;
}
0
def linear_search(a, key):
	position = 0
	flag = False
	while position < len(a) and not flag:
		if a[position] == key:
			flag = True
		else:
			position = position + 1
	return flag
0

New to Communities?

Join the community