-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBinarySearchFoundInsert.cpp
More file actions
73 lines (64 loc) · 1.57 KB
/
BinarySearchFoundInsert.cpp
File metadata and controls
73 lines (64 loc) · 1.57 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
62
63
64
65
66
67
68
69
70
71
72
73
#include <bits/stdc++.h>
using namespace std;
int binarySearch(int* arr, int low, int high, int x) {
if (high >= low) {
int mid = low + (high - low) / 2;
if (arr[mid] == x) {
return mid;
}
else if (arr[mid] > x) {
return binarySearch(arr, low, mid - 1, x);
}
else {
return binarySearch(arr, mid + 1, high, x);
}
}
return -1;
}
void insertElement(int* arr, int& size, int k, int x) {
size++;
for (int i = size - 1; i > k; i--) {
arr[i] = arr[i - 1];
}
arr[k] = x;
}
void deleteElement(int* arr, int& size, int x) {
int pos = binarySearch(arr, 0, size - 1, x);
if (pos == -1) {
cout << "Element not found in the array." << endl;
return;
}
for (int i = pos; i < size - 1; i++) {
arr[i] = arr[i + 1];
}
size--;
}
int main() {
int size;
cout << "Enter the size of the array: ";
cin >> size;
int* arr = new int[size];
cout << "Enter the elements of the array: ";
for (int i = 0; i < size; i++) {
cin >> arr[i];
}
int x;
cout << "Enter the element to search for: ";
cin >> x;
int pos = binarySearch(arr, 0, size - 1, x);
if (pos == -1) {
int k;
cout << "Enter the position to insert the element: ";
cin >> k;
insertElement(arr, size, k, x);
}
else {
deleteElement(arr, size, x);
}
cout << "Modified array: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
delete[] arr;
return 0;
}