Arrays: Deletion with searching in C++
Sakshi
Posted on September 18, 2021
I was practising arrays in C++, for competitive programming. While coding for basic operations, I thought to code for deleting elements while searching for them.
Jumped to google and after searching for like 30 minutes, I got no stuff related except one article from GFG, which showed me a complex code. But the code from GeeksforGeeks didn't run when array contained same value elements. Without wasting time on searching, I started writing algorithm for the solution I want.
And after an hour, I was able to write an algorithm which works for array with same elements, and array with different elements.
I don't know whether solution is available on internet or not, it must be there, but hard to find. See if my solution helps in this, although the time complexity of this solution is not as efficient as it should be.
The program doesn't include any STL functions, since I am a beginner in DSA with C++ twice.
Link to GFG solution : https://www.geeksforgeeks.org/delete-an-element-from-array-using-two-traversals-and-one-traversal/
Code:
int deleteSearch(int a[],int n, int val){
// val is value to be searched
// n is the size of static array
int i = 0;
while( i < n){
if(a[i] == val) {
//shifting and deleting elements
while(i < n){
a[i] = a[i+1];
i++;
}
n--;
i = 0;
}
else
i++;
}
return n;
}
The program works for all cases. Please share you views,corrections and solutions.
Posted on September 18, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.