Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program with at least 3 functions. One function can do a linear search o

ID: 3692537 • Letter: W

Question

Write a program with at least 3 functions. One function can do a linear search on an array. The other can do a binary search. You will need to modify the binary search code to keep track of how many numbers it checked before it found the number. Use function header/prototypes. In main, make an array of 30 sorted numbers. (Initialize the array with the numbers.) Do searches on the arrays on the same numbers. Print out how many elements it needs to check before it finds the number with each type of search. Do at least 6 linear searches and 6 binary searches.

Explanation / Answer

PROGRAM:

#include <stdio.h>
int linear_search(int [], int, int);
int binary_search(int[], int, int, int);
int main(){
int a[30] = { 1, 3, 7, 10, 12, 15, 23, 31, 44, 51, 56, 63, 66, 70, 75, 80, 81, 89, 90, 93, 97, 99, 105, 119, 121, 130, 149, 155, 170, 190};
int i,n=30,num,low,high;

printf("Enter the number to be search: ");
scanf("%d",&num);
linear_search(a, n, num);
low = 0;
high = n - 1;
binary_search(a, num, low, high);
return 0;
}
int count=0;
int linear_search(int a[], int n, int num) {
int i;

for (i = 0 ;i < n ; i++ ) {
count = count + 1;
if (a[i] == num)
printf("The number is found after %d linear searches ", count);
}
return 0;
}
int count1=0;
int binary_search(int a[], int num, int low, int high) {
int mid;

if (low <= high) {
mid = (low + high) / 2;
  
if (num == a[mid]) {
count1 = count1 +1;
printf("The number is found after %d binary searches", count1);
}
else if (num < a[mid]) {
count1 = count1 +1;
binary_search(a, num, low, mid - 1);
}
else {
count1 = count1 +1;   
binary_search(a, num, mid + 1, high);
}
}
}

OUTPUT:

The number is fount after 22 linear searches

The number is found after 5 binary searches

Enter the number to be search : 1

The number is fount after 1 linear searches

The number is found after 4 binary searches

Enter the number to be search : 15

The number is fount after 6 linear searches

The number is found after 5 binary searches

Enter the number to be search : 66

The number is fount after 13 linear searches

The number is found after 4 binary searches

Enter the number to be search : 75

The number is fount after 15 linear searches

The number is found after 1 binary searches

Enter the number to be search : 90

The number is fount after 19 linear searches

The number is found after 3 binary searches

Enter the number to be search : 190

The number is fount after 30 linear searches

The number is found after 5 binary searches

  

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote