chore(CPlusPlus): add linear search for recursion and two dimension array (#630)

pull/637/head
Samruddhi Ghodake 2021-11-13 06:03:29 +05:30 committed by GitHub
parent d38e965e1b
commit 5d8fbc07b5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 106 additions and 0 deletions

View File

@ -29,6 +29,7 @@
- [Merge two sorted array without using extraspace](Arrays/merge-two-sorted-array.cpp)
- [All unique triplet that sum up to given value](Arrays/three-sum.cpp)
- [Next permutation](Arrays/next-permutation.cpp)
## Dynamic-Programming
- [Longest Common Subsequence](Dynamic-Programming/longest-common-subsequence.cpp)
@ -77,6 +78,7 @@
- [Ternary Search](Searching/Ternary-search.cpp)
- [Interpolation Search](Searching/interpolation-search.cpp)
- [Exponential Search](Searching/exponential-search.cpp)
- [Linear search in 2D array](Searching/linear-search-in-2d.cpp)
## Stacks
@ -176,3 +178,4 @@
- [Array sorted or not](Recursion\array-sorted-or-not.cpp)
- [Product of two numbers](Recursion\product-of-numbers.cpp)
- [Product of digits in a number](Recursion\product-of-digits.cpp)
- [Linear search using recursion](Recursion/linear-search.cpp)

View File

@ -0,0 +1,48 @@
/*
Description: linear search using recursion
Time Complexity: O(n) where n is the number of elements in the array
*/
#include <iostream>
#include <vector>
using namespace std;
//function starts
int linearSearch(vector<int> arr, int i, int n, int target)
{
//base case
if (i == n)
{
return -1;
}
//if the ith element in the array is equal to the target, return the index
if (arr[i] == target)
{
return i;
}
//recursive function call
//i refers to the index that we will need to check the element in the array
//at every recursive call we will increment the i by 1
return linearSearch(arr, i + 1, n, target);
}
//main starts
int main()
{
vector<int> arr = {1, 2, 3, 4, 5};
int n = arr.size();
int target = 3;
cout << linearSearch(arr, 0, n, target);
return 0;
}
/*
Input:
arr = [1,2,3,4,5]
target = 3
Output:
2
*/

View File

@ -0,0 +1,55 @@
/*
Description: program to perform linear search in 2d array
Time complexity: O (m*n) where m is the number of rows and n refers to the number of columns
*/
#include <iostream>
#include <vector>
using namespace std;
//function starts
void linearSearch(vector<vector<int>> arr, int target)
{
//for every row
for (int i = 0; i < arr.size(); i++)
{
//for every element in the row, i.e column
for (int j = 0; j < arr[i].size(); j++)
{
//check if the element in the array is equal to the target
if (arr[i][j] == target)
{
cout << i << " " << j; //print it
return;
}
}
}
cout << "Element not found"; //else print element not found
}
//main starts
int main()
{
vector<vector<int>> arr = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}}; //array
int target = 9; //element need to be search
linearSearch(arr, target); //calling the function
return 0;
}
/*
Input:
arr = [
[1,2,3],
[4,5,6],
[7,8,9]
]
target = 9
Output: 2 2
*/