Examples:
Input:
arr[ ] : {1,2,3,4,5,6,7,8}
delete = 3;
Output:
arr[ ] : {1,2,4,5,6,7,8}
#include <bits/stdc++.h>
using namespace std;
// To search a num to be deleted
int binarySearch(int arr[], int l, int r, int num);
/* Function to delete an element */
int deleteElement(int arr[], int n, int num)
{
int pos = binarySearch(arr, 0, n - 1, num);
if (pos == -1)
{
cout << "Element not found";
return n;
}
// Deleting element
int i;
for (i = pos; i < n - 1; i++)
arr[i] = arr[i + 1];
return n - 1;
}
int binarySearch(int arr[], int l, int r, int num)
{
if (r < l)
return -1;
int mid = (l + r) / 2;
if (num == arr[mid])
return mid;
if (num > arr[mid])
return binarySearch(arr, (mid + 1), r, num);
return binarySearch(arr, l, (mid - 1), num);
}
// Driver code
int main()
{
int i;
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int num = 3;
cout << "Array before deletion\n";
for (i = 0; i < n; i++)
cout << arr[i] << " ";
// Function call
n = deleteElement(arr, n, num);
cout << "\n\nArray after deletion\n";
for (i = 0; i < n; i++)
cout << arr[i] << " ";
}
Output:
Array before deletion
1 2 3 4 5
Array after deletion
1 2 4 5
0 Comments