You are on page 1of 1

1 #include <stdio.

h>
2
3 int binary_search_insert(int arr[], int n, int v) {
4 int low = 0;
5 int high = n - 1;
6
7 while (low <= high) {
8 int mid = (low + high) / 2;
9
10 if (arr[mid] > v) {
11 high = mid - 1;
12 } else if (arr[mid] < v) {
13 low = mid + 1;
14 } else {
15 return mid;
16 }
17 }
18
19 return low;
20 }
21
22 int main() {
23 int arr[] = {1, 3, 5, 7, 9};
24 int n = sizeof(arr) / sizeof(arr[0]);
25 int v = 4;
26
27 int position = binary_search_insert(arr, n, v);
28
29 // Shift elements to the right to make space for the new value
30 for (int i = n - 1; i >= position; i--) {
31 arr[i + 1] = arr[i];
32 }
33
34 arr[position] = v;
35 n++; // Increase the size of the array
36
37 // Print the resulting array
38 for (int i = 0; i < n; i++) {
39 printf("%d ", arr[i]);
40 }
41 printf("\n");
42
43 return 0;
44 }

Answer.ai

You might also like