Answer to Question #237504 in C for Aadi

Question #237504
Design a recursive algorithm to search a sorted array a for an element x between a[low] and
a[high]. If no element is found it returns -1. Also, analyse the time and space complexity of your
algorithm.
1
Expert's answer
2021-09-15T05:16:15-0400
# include<stdio.h>

int RecursiveSearch(int arr[], int size, int k)
{
    int loc;
    if (arr[size] == k)		return size;
    else if (size == -1)    return -1;
    else				    return (loc = RecursiveSearch(arr, size - 1, k));
}


int main()
{
    int size, index, key;
    int a[] = {2, 5, 11, 23, 34, 45, 56, 67, 78, 89};
    int count = 0;
    int i;
 
 	index = sizeof(a)/sizeof(a[0]);
    printf("\nInput List: ");
    for (i = 0; i < index; i++)       printf("%d\t", a[i]);
    printf("\nEnter the key to search: ");    scanf("%d", &key);
    while (index > 0)
    {
        index = RecursiveSearch(a, index - 1, key);
        if(index >=0) 
		{
			printf("Key found at position: %d\n", index + 1);
        	count++;			
		}
    }
    if (!count)
        printf("Key not found.\n");
    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