Binary Search (Recursive)



	#include <stdio.h>

	// Function Prototypes
	int binSearchWrapper(int arr[], int target, int len);
	int binSearchRec(int arr[], int target, int left, int right);

	// Calls recursive binary search function
	int binSearchWrapper(int arr[], int target, int len) {
		return binSearchRec(arr, target, 0, len - 1);
	}

	// Recursive binary search
	// Returns 1 if target is in array, otherwise returns 0
	int binSearchRec(int arr[], int target, int left, int right) {
		if (left > right)
			return 0;

		int mid = (left + right) / 2;

		if (arr[mid] == target)
			return 1;

		if (target < arr[mid])
			return binSearchRec(arr, target, left, mid - 1);
		else
			return binSearchRec(arr, target, mid + 1, right);
	}

	int main(void) {
		int len = 20;
		int arr[] = {3,  6,  7,  11, 25, 32,  33,  33,  46,  52,
								 79, 83, 88, 91, 94, 101, 107, 112, 122, 148};
		int choice = 0;
		while (choice >= 0) {
			printf("Enter positive integer to see if it exists in the array\n(Enter "
						 "negative value to exit)\n:");
			scanf("%d", &choice);
			if (choice < 0)
				break;
			printf("%d is %sin the array.\n\n", choice,
						 binSearchWrapper(arr, choice, len) ? "" : "NOT ");
		}
		return 0;
	}
						
						

Academic Notice: The code shown here is provided solely as a learning reference. Copying and pasting is intentionally disabled to encourage independent practice. Students should implement solutions on their own to demonstrate understanding. This material is not intended for direct submission in assignments.

Additionally: This code was written by a former CS1 student and may not reflect your professor’s intended solution or instructional approach. For coursework, students are expected to follow examples, conventions, and requirements presented in class and in professor-assigned materials.