Answer to Question #288682 in C for Bryan

Question #288682

A c program that carries out binary search of an element entered by the user in an array of elements and then displace the location of that element else if not found it displace element not found.

1
Expert's answer
2022-01-19T10:36:09-0500
#include <stdio.h>








int main()
{
	int i,j,c, first, last, middle, n, search,temp;
	int elements[100];


	printf("Enter number of elements: ");
	scanf("%d", &n);






	for (c = 0; c < n; c++){
		printf("Enter integer number %d: ",c);
		scanf("%d", &elements[c]);
	}


 
	for(i = 0 ; i < n - 1; i++)
	{
		for(j = 0 ; j < n-i-1; j++)
		{
			if(elements[j] > elements[j+1]) 
			{
				temp=elements[j];
				elements[j]=elements[j+1];
				elements[j+1]=temp;
			}
		}
	} 
	printf("Sorted numbers:\n");
	for (c = 0; c < n; c++){
		printf("%d ",elements[c]);
	}




	printf("\n\nEnter value to search: ");
	scanf("%d", &search);


	first = 0;
	last = n - 1;
	middle = (first+last)/2;


	while (first <= last) {
		if (elements[middle] < search)
			first = middle + 1;
		else if (elements[middle] == search) {
			printf("%d found at location %d.\n", search, middle);
			break;
		}
		else
			last = middle - 1;


		middle = (first + last)/2;
	}
	if (first > last)
		printf("Not found! %d isn't present in the list.\n", search);




	getchar();
	getchar();
	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