Question

What is wrong with my recursive Binary Search code? For some reason my 'middle' value is...

What is wrong with my recursive Binary Search code? For some reason my 'middle' value is always zero? Please fix and explain!

#include <stdio.h>

#include <stdlib.h>

#include <stdbool.h>


int BinarySearch(const int A[],const int L,const int R,const int key)
{

  
      

   if (R >= 1){
      
   int middle = L + (R-1)/2;
          
          
       if (A[middle] == key)
       return A[middle];
      
       if (A[middle] > key){
       BinarySearch(A, L, middle -1, key);}
      
       if (A[middle] < key){
       BinarySearch(A, L, middle + 1, key);}
}
   else{
   return -1;} //No element in the array
  
}


//------------------------------------------------------------

int main()

//------------------------------------------------------------

{

int BinarySearch(const int A[],const int L,const int R,const int key); //Calls function

int n;

printf("n? ");

while ( scanf("%d",&n) != EOF ) //while n doesn't equal eof

{

int i,key,*A = (int *) malloc(sizeof(int)*n); // define i, key, pointer A
  
//Array A is an integer array that is the size of integer n

for (i = 0; i <= n-1; i++){ //fills array
       A[i] = 2*(i+1);}

for (key = 1; key <= 2*n; key++){ //create key
    printf("%3d at %4d\n",key,BinarySearch(A,0,n-1,key)); }

free(A); //free the memeroy from the heap of the array A

printf("\nn? ");

}

system("PAUSE");

return( 0 );

}

Homework Answers

Answer #1

so there are some wrong code in BinarySearch function here they are

int BinarySearch(const int A[],const int L,const int R,const int key)
{


if (R >= 1){ // this condition is wrong because what if L >=R and R>=1 this will always give a wrong answer
   // so the correct condition is" if(L<R) " because it should only work when the left is less than right
  
int middle = L + (R-1)/2; // this is correct this method is used to overcome the overflow
  
  
if (A[middle] == key) // this condition is also correct
return A[middle];
  
if (A[middle] > key){ // for this condition A[middle]>key it means you have to go to left for this condition, only right value will change
//right value it will be "middle-1" , which you have already specified   
  
//this line is correct
BinarySearch(A, L, middle -1, key);}
  
if (A[middle] < key){ // for this line" A[middle] < key " so now it will go to right so for that condition only left value will change and that will be middle+1
//this line is wrong
BinarySearch(A, L, middle + 1, key);} // it should be BinarySearch(A, middle + 1, R, key);


}
else{
return -1;} //No element in the array
  
}

//rest of the code is as it is ..... so these were the lines where you wrote the wrong code.
one advise after writing code do run code once by taking simple examples and check for the output

if any doubt, comment below

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Using the C programming language implement Heapsort in the manner described in class. Here is some...
Using the C programming language implement Heapsort in the manner described in class. Here is some example code to use as a guideline. Remember, you need only implement the sort algorithm, both the comparison and main functions have been provided. /* * * after splitting this file into the five source files: * * srt.h, main.c, srtbubb.c, srtinsr.c, srtmerg.c * * compile using the command: * * gcc -std=c99 -DRAND -DPRNT -DTYPE=(float | double) -D(BUBB | HEAP | INSR |...
Expand the code below to display both the value of the loop variable and this value...
Expand the code below to display both the value of the loop variable and this value squared. Put the pairs of values on a new line. #include <stdio.h> #include <stdlib.h> int main(void) { int i; int a; int b; do { printf("Please enter the lower value: "); scanf("%d", &a); printf("Please enter the upper value: "); scanf("%d", &b); if (a>b) printf("The upper value must be greater than the lower value\n\n"); } while (a>b); for(i=a; i<=b; i++) printf("%d ", i); return 0;...
IN C PROGRAMMING A Tv_show structure keeps track of a tv show’s name and the channels...
IN C PROGRAMMING A Tv_show structure keeps track of a tv show’s name and the channels (integer values) that broadcast the show. For this problem you can ONLY use the following string library functions: strcpy, strlen, strcmp. You MAY not use memcpy, memset, memmove. You can assume memory allocations are successful (you do not need to check values returned by malloc nor calloc). typedef struct tv_show { char *name; int num_channels, *channels; } Tv_show; a. Implement the init_tv_show function that...
This is my code and can you please tell me why it's not working? By the...
This is my code and can you please tell me why it's not working? By the way, it will work if I reduce 10,000,000 to 1,000,000. #include <iostream> using namespace std; void radixSort(int*a, int n) { int intBitSize = sizeof(int)<<3; int radix = 256; int mask = radix-1; int maskBitLength = 8;    int *result = new int[n](); int *buckets = new int[radix](); int *startIndex = new int[radix]();    int flag = 0; int key = 0; bool hasNeg =...
#include<stdio.h> int main() {       /* For binary search, the array should be arranged in ascending...
#include<stdio.h> int main() {       /* For binary search, the array should be arranged in ascending or descending order */       int data[] = {1,2,3,4,5,6,7,8,9,10}; ****You might change the numbers for your program also       /* 'min' use for starting location of the array, 'max' use for end location of the array and 'mid' use for middle location of the array */       int min = 0, max = 10, search, mid = (max + min) / 2;       printf("Enter...
Considering the following code fragment: #include<stdio.h> #include <stdlib.h> int base = 0; static int bonus; int*...
Considering the following code fragment: #include<stdio.h> #include <stdlib.h> int base = 0; static int bonus; int* demage (int dmg) { int* ptr = (int*) malloc(sizeof(int)); static int constant = 1;   *ptr = dmg + constant; return ptr; } int main() { int HP = 0; int* dm; base = 30; bonus = 20; for(int i=1; i<4; i++) { HP += i * base; } dm = demage(10); HP += bonus - *dm; printf("Total HP: %i", HP); return 0; } Please...
Q3) Write a function that takes two arrays and their size as inputs, and calculates their...
Q3) Write a function that takes two arrays and their size as inputs, and calculates their inner product (note that both arrays must have the same size so only one argument is needed to specify their size). The inner product of two arrays A and B with N elements is a scalar value c defined as follows: N−1 c=A·B= A(i)B(i)=A(0)B(0)+A(1)B(1)+···+A(N−1)B(N−1), i=0 where A(i) and B(i) are the ith elements of arrays A and B, respectively. For example, theinnerproductofA=(1,2)andB=(3,3)isc1 =9;andtheinnerproductofC= (2,5,4,−2,1)...
#include <stdio.h> extern unsigned long long sum(unsigned int *array, size_t n); int main(void) { unsigned int...
#include <stdio.h> extern unsigned long long sum(unsigned int *array, size_t n); int main(void) { unsigned int array[] = { 1, 1, 1, 3 }; unsigned long long r = sum(array, sizeof(array) / sizeof(*array)); printf("Result is: %llu (%s)\n", r, r == 6 ? "correct" : "incorrect"); return 0; } Complete the code for the line that calls the sum function. Write the sum function.
For the following code in C, I want a function that can find "america" from the...
For the following code in C, I want a function that can find "america" from the char array, and print "america is on the list" else "america is not on the list" (Is case sensitive). I also want a function to free the memory at the end of the program. #include <stdio.h> #include <stdlib.h> struct Node { void *data; struct Node *next; }; struct List { struct Node *head; }; static inline void initialize(struct List *list) { list->head = 0;...
Error compiler. need fix code for febonacci Iterative like 0 1 1 2 3 5 8...
Error compiler. need fix code for febonacci Iterative like 0 1 1 2 3 5 8 13 21 34 55 ....... and also need add code complexity time if you want! here code.c --------------------------------------------------------------------------------------------------------------------- #include <stdio.h> #include <math.h> int fibonacciIterative( int n ) { int fib[ n + 1 ]; int i; fib[ 0 ] = 0; fib[ 1 ] = 1; for ( i = 2; i < n; i++ ) { fib[ i ] = fib[ i -...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT