DEV Community

Cover image for Arrays: Deletion with searching in C++
Sakshi
Sakshi

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.

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;
 }

Enter fullscreen mode Exit fullscreen mode

The program works for all cases. Please share you views,corrections and solutions.

Top comments (2)

Collapse
 
sbgssol profile image
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)

Collapse
 
rborajov profile image
Roschek Borajov

I like your dedication... Keep it up

Some comments have been hidden by the post's author - find out more