-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeletion.cpp
More file actions
61 lines (46 loc) · 1.09 KB
/
deletion.cpp
File metadata and controls
61 lines (46 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// C++ program to implement delete operation in an unsorted array
#include <iostream>
using namespace std;
// To search a key to be deleted
int findElement(int arr[], int n, int key);
// Function to delete an element
int deleteElement(int arr[], int n, int key)
{
// Find position of element to be deleted
int pos = findElement(arr, n, key);
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;
}
// Function to implement search operation
int findElement(int arr[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;
return -1;
}
// Driver's code
int main()
{
int i;
int arr[] = { 10, 50, 30, 40, 20 };
int n = sizeof(arr) / sizeof(arr[0]);
int key = 30;
cout << "Array before deletion\n";
for (i = 0; i < n; i++)
cout << arr[i] << " ";
// Function call
n = deleteElement(arr, n, key);
cout << "\n\nArray after deletion\n";
for (i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}