Searching Elements in an Array | Array Operations

1 min read
Solved my 1 st Question from the coder army sheet today on the Geeks for Geeks platform Sheet has more than 700+ amazing problem
Todays Problem
/
Search an Element in an array |
Check if two arrays are equal or not |
Missing element of AP |
Cyclically rotate an array by one |
// linear serch
int search(int arr[], int N, int X){
int result = -1;
for(int i=0; i<N ; i++){
if(arr[i] == X) return result = i;
}
return result;
}
// binary serching
int search(int arr[], int N, int X){
int start = 0;
int end = N-1;
int mid;
Arrays.sort(arr);
while(start<=end){
mid=(end-start)/2+start;
if(arr[mid]==X) return mid;
else if(arr[mid]>X) end= mid-1;
else start = mid+1;
}
return -1;
}
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int N = 18,X=43;
int arr[] = {1,7,6,4,5,2,3,8,11,34,54,23,86,51,90,66,89,43};
sort(arr,arr+N);
int start = 0;
int end = N -1;
int mid ;
while(start<end){
mid = (start + end ) / 2;
if(arr[mid] == X){ cout << "find" << mid ;break;}
else if(arr[mid] < X){ start = mid; ;}
else if(arr[mid] > X){ end = mid; }
cout << mid << arr[mid] << X << endl;
}
return 0;
}
0
Subscribe to my newsletter
Read articles from karan arora directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
