Problem Solving: Brute Force Searching III
Learn how to use the brute force searching technique to find all the occurrences of an element in an array.
We'll cover the following
Search problems
In this lesson, we will learn to solve a search problem using arrays. Write your code in the playground here. We have provided you the main()
function and all the required prototypes of the functions. Uncomment the code lines in the main()
function after each task is done, and test whether your program is working correctly or not.
Exercise playground
Please write your code in the given playground.
2 3 4 1 2 1 5 -1
Searching all the occurrences
Task: Find all the indices of an element in an array.
Sample input
Data: { 2 3 4 1 2 1 5 }
Program: Searching problemsData: { 2 3 4 1 2 1 5 }------------------------------------------Searching all the Occurence of: 22 is found at { 0 4 }
Let’s implement a function findAllIndices()
.
void findAllIndices(int D[ ], int size, int t, int Is[], int &sizeIs)
- To find the target element
t
, we passD[]
andsize
because we need to perform the search on the data present in the arrayD[]
, whilesize
shows the number of elements present in the array. Is[]
is the array in which the function will write all the indices where the occurrences of the target element are found, andsizeIs
shows the count of found occurrences, i.e., how many times the value is found.
Idea:
- We will first initialize
sizeIs
to 0, as we need to update the garbage value inside the variable. - We will iterate through each element present in
D[]
.- We’ll check if
D[i] == t
. Then we will save this indexi
inside the indices array atIs[sizeIs] = i
. - Along with that, we’ll increment
sizeIs
so that now the next index found should be stored at the next memory location. - With
sizeIs
, we keep track of how often the target elementt
is found inside the dataD[]
.
- We’ll check if
void findAllIndices(int D[ ], int size, int t, int Is[], int &sizeIs){sizeIs = 0;for(int i=0; i<size; i++){if(D[i]==t){Is[sizeIs] = i;sizeIs++;}}}
Instruction: Write the code in the exercise playground and test it.
Quiz
What is the function going to return?
int f1(int D[], int size, int t)
{
int fi = -1;
for(int i=0; i<size; i++)
{
if(D[i]==t)
fi = i;
}
return fi;
}
int main()
{
int D[] = {1,2,3,2,3,1}, size = 6, t=3;
cout << f1(D, size, t);
return 0;
}
The first occurrence of t
in the data D[ ]
.
The last occurrence of t
in the data D[ ]
.
It will always return -1
.