Answer to Question #174409 in C for shakib

Question #174409

Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.


Ex 1:

 

Input: num = [1,3,5,6], target = 5

Out: 2

 

Ex 2:

 

Input: num = [1,3,5,6], target = 2

Out: 1

 

Ex 3:

 

Input: num = [1,3,5,6], target = 7

Out: 4

 

 

Ex 4:

 

Input: num = [1,3,5,6], target = 0

Out: 0

 

Ex 5:

 

Input: num = [1], target = 0

Out: 0


please follow the below program finish it in C language.


#include <stdio.h>
#include <stdlib.h>

int nums[1024]; 

int main(){
	FILE *fp;
  fp=fopen("binarysearch.txt","r");
  if(fp==NULL){
  	printf("The input file does not exist.\n");
  	exit(-1);
  }
  int target,size = 0,i; 
  fscanf(fp, "%d", &target);
	while (!feof(fp)){  
  	fscanf(fp, "%d", &(nums[size])); 
  	size ++;
}
1
Expert's answer
2021-03-22T14:17:47-0400
#include <stdio.h>
#include <stdlib.h>

int nums[1024]; 

int binarysearch(int A[], int size, int target) {
  int l=0, r=size-1, m;
  while (l <= r) {
    m = (r + l) / 2;
    if (A[m] == target)
      return m;
    if (A[m] < target)
      l = m+1;
    else
      r = m-1;
  }
  if (A[m] < target)
    return m+1;
  else
    return m;
}

int main(){
    FILE *fp;
  fp=fopen("binarysearch.txt","r");
  if(fp==NULL){
    printf("The input file does not exist.\n");
    exit(-1);
  }
  int target,size = 0,i; 
  fscanf(fp, "%d", &target);
  while (!feof(fp)){  
    fscanf(fp, "%d", &(nums[size])); 
    size++;
  }
  fclose(fp);

  printf("%d\n", binarysearch(nums, size, target));

  return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS