Delete an element from array using two traversals and one traversal in C++?

C++Server Side ProgrammingProgramming

Two Traversals 

Let us first define the original array and the element to be searched and deleted from the array −

int ele = 5;
int arr = [1,2,3,4];

Now we loop in the array to find the given element −

for (i=0; i<length; i++)
   if (arr[i] == ele) break;

If the given element position is found then we shift the elements to left which are in right to the found element −

if (i < length) {
   length--;
      for (int j=i; j<length; j++)
         arr[j] = arr[j+1];
}

Example

Let us see the following implementation to see the deletion of element in the array in two traversals −

 Live Demo

#include<iostream>
using namespace std;

int main() {
   int arr[] = {11, 15, 6, 8, 9, 10};
   int length = sizeof(arr)/sizeof(arr[0]);
   int ele = 6;

 int i;
   for (i=0; i<length; i++)
      if (arr[i] == ele) break;

   if (i < length) {
   length--;
      for (int j=i; j<length; j++)
         arr[j] = arr[j+1];
   }
   cout << "The array after deletion is "<<endl;
   for (int i=0; i<length; i++)
      cout << arr[i] << " ";

   return 0;
}

Output

The above code will produce the following output −

The array after deletion is
11 15 8 9 10

One Traversal

Let us first define the original array and the element to be searched and deleted from the array −

int ele = 15;
int arr = [11,15,6,8,9,10];

Now we declare two variables Boolean found which specifies if the element is found or not and int pos which will store the element position if found −

bool found=false;
int pos=-1;

Next, we search the array and if an element is found we store its position and shift elements while our loop is traversing in a single go.

for (int i=0; i<length; i++){
   if(pos!=-1){
      arr[pos]=arr[pos+1];
      j++;
   }
   else if(arr[i]==ele){
      pos=i;
      found=true;
   }
}

Example

Let us see the following implementation to see the deletion of element in the array in one traversal only −

 Live Demo

#include<iostream>
using namespace std;

int main() {
   int arr[] = {11, 15, 6, 8, 9, 10};
   int length = sizeof(arr)/sizeof(arr[0]);
   int ele = 6 ;

bool found=false;
int pos=-1;
   for (int i=0; i<length; i++){
      if(pos!=-1){
         arr[pos]=arr[pos+1];
         pos++;
      }
      else if(arr[i]==ele){
         pos=i;
         found=true;
      }
   }
   cout << "The array after deletion is "<<endl;
   if(found){
      length--;
   }
   for (int i=0; i<length; i++)
      cout << arr[i] << " ";
   return 0;
}

Output

The above code will produce the following output −

The array after deletion is
11 15 8 9 10
raja
Published on 16-Jan-2021 11:16:02
Advertisements