## DEV Community is a community of 756,027 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Bellatrix

Posted on

# Arrays: Deletion with searching in C++

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.

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.

## Discussion (2)

Ly Nguyen

I appreciate the way you search and solve your problem. Keep going.
About the second solution on GFG, I think it's a good solution for us for reference, although there is a limitation that the target number must represent in the array. (y)

Roschek Borajov

I like your dedication... Keep it up