****** I AM ASKING FOR AN ANSWER IN HASKELL PLEASE READ THE QUESTION CAREFULLY S
ID: 3707766 • Letter: #
Question
****** I AM ASKING FOR AN ANSWER IN HASKELL PLEASE READ THE QUESTION CAREFULLY
SE and Programming 2090- Extra Work for Practice
Write a function in HASKELL to do the following...
Recursive Binary Search - binary_search(data, item, offset)
Takes a sorted list, data, and performs a recursion binary search of data for the element item. If found, returns the index where the item is found. If not found, returns –1. offset is a variable used for recursive calls to record the offset from the original data. The function will always be initially called with this set to 0. You are permitted to use the following functions:
take n alist - returns, as a list, the first n items in an alist
drop n alist = returns a list without the first n items of alist
quot num divisor - returns the quotient of num / divisor
length alist - returns the length of a list
mathematical/comparison operations (+, -, <, etc.)
!! - list index operator
Template:
Examples:
Explanation / Answer
CODE
#include <stdio.h>
int binarySearch(int arr[], int i, int j, int x)
{
if (j >= i)
{
int mid = i + (j - i)/2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, i, mid-1, x);
return binarySearch(arr, mid+1, j, x);
}
return -1;
}
int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 10;
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;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.