My issue
Please help me to solve as soon as possible
My code
#include <stdio.h>
// Function to perform binary search and find the index or insertion position
int searchInsertPosition(int arr[], int n, int target) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2; // Prevent overflow
if (arr[mid] == target) {
return mid; // Target found
} else if (arr[mid] < target) {
left = mid + 1; // Move to the right
} else {
right = mid - 1; // Move to the left
}
}
return left; // Return the position where the target would be inserted
}
int main() {
int n, q;
// Input size of the array and number of queries
scanf("%d %d", &n, &q);
int arr[n];
// Input the sorted array
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Process each query
for (int i = 0; i < q; i++) {
int target;
scanf("%d", &target);
// Call the binary search function and print the result
printf("%d\n", searchInsertPosition(arr, n, target));
}
return 0;
}
Learning course: Data structures & Algorithms lab
Problem Link: https://www.codechef.com/learn/course/muj-dsa-c/MUJDSAC20A/problems/DSAAGP1094