Delete an element from array (Using two traversals and one traversal) - GeeksQuiz
Given an array and a number 'x', write a function to delete 'x' from the given array.
Two Traverse
Can we delete the element using one traversal?
The idea is to start from right most element and keep moving elements while searching for ‘x
Read full article from Delete an element from array (Using two traversals and one traversal) - GeeksQuiz
Given an array and a number 'x', write a function to delete 'x' from the given array.
Two Traverse
int deleteElement(int arr[], int n, int x){ // Search x in array int i; for (i=0; i<n; i++) if (arr[i] == x) break; // If x found in array if (i < n) { // reduce size of array and move all // elements on space ahead n = n - 1; for (int j=i; j<n; j++) arr[j] = arr[j+1]; } return n;}The idea is to start from right most element and keep moving elements while searching for ‘x
// Returned size is n-1 when element is present.// Otherwise 0 is returned to indicate failure.int deleteElement(int arr[], int n, int x){ // If x is last element, nothing to do if (arr[n-1] == x) return (n-1); // Start from rightmost element and keep moving // elements one position ahead. int prev = arr[n-1], i; for (i=n-2; i>=0 && arr[i]!=x; i--) { int curr = arr[i]; arr[i] = prev; prev = curr; } // If element was not found if (i < 0) return 0; // Else move the next element in place of x arr[i] = prev; return (n-1);}