Linear Search
RELATED POSTS
- Blogger Comment
- Facebook Comment
Subscribe to:
Post Comments
(
Atom
)
C/C++,java,python c++ keywords, identifiers, data types,variables,modifiers,storage classes,operators,for loop ,while loop,do while loop,if else statement,nested loops,break continue goto statement,functions ,call by value call by reference ,arrays ,strings,pointers,data structures ,classes and objects,inheritance,polymorphism,operator overloading,function overloading,data abstraction,data encapsulation,dynamic memory allocation for array and objects,function templates,class templates,
Linear Search
The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.
First line of each test case or query contains an integer 'N' representing the size of the array/list.
Second line contains 'N' single space separated integers representing the elements in the array/list.
Third line contains the value of X(integer to be searched in the given array/list)
For each test case, print the index at which X is present or -1, otherwise.
Output for every test case will be printed in a separate line.
1 <= t <= 10^2
0 <= N <= 10^5
-2 ^ 31 <= X <= (2 ^ 31) - 1
Time Limit: 1 sec
1
7
2 13 4 1 3 6 28
3
4
2
7
2 13 4 1 3 6 28
9
5
7 8 5 9 5
5
-1
2
c++ code:
// arr - input array
// n - size of array
// val - element to be searched
int linearSearch(int arr[], int n ,int val){
for(int i=0; i<n; i++)
{
if(arr[i]==val)
{
return i;
}
}
return -1;
}
0 comments:
Post a Comment