Question

2) Write a recursive procedure in pseudocode to implement the binary search algorithm. 3) Explain, how the binary search algo

0 0
Add a comment Improve this question Transcribed image text
Answer #1

1.Recursive procedure in pseudocode to implement a binary search algorithm

// C program to implement recursive Binary Search
#include <stdio.h>
int binarySearch(int arr[], int l, int r, int x)
{
   if (r >= l) {
       int mid = l + (r - l) / 2;  
       if (arr[mid] == x)
           return mid;  
       if (arr[mid] > x)
           return binarySearch(arr, l, mid - 1, x);
       return binarySearch(arr, mid + 1, r, x);
   }
   return -1;
}

int main(void)
{
   int arr[] = { 1,2,4,5};
   int n = sizeof(arr) / sizeof(arr[0]);
   int x = 3;
   int result = binarySearch(arr, 0, n - 1, x);
   (result == -1) ? printf("Element is not present in array")
               : printf("Element is present at index %d",
                           result);
   return 0;
}

2. To insert an element into a sorted array using binary search

In order to insert a random number into a sorted array using binary search first, we compare the number with mid, if the mid is greater than that number then right=mid otherwise lenft=mid-1. After this step, we again call the same function as this is a recursive function. This loop is completed when left<right and then we add the number in the place of left.

 public void add(T e, int result) {
        int left, right, mid;


        left = 0;
        right = array.size();


        while(left< right)  {
            mid = (left + right)/2;
            


            if(result > 0) { //If e is lower
                right = mid;
            } else { //If e is higher
                left = mid + 1;
            }
        }

        array.add(left, e);

    }
Add a comment
Know the answer?
Add Answer to:
2) Write a recursive procedure in pseudocode to implement the binary search algorithm. 3) Explain, how...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT