//write a program in c to Implement Binary search and //Linear Search #include #include int main() { int a[20], size, ch, n, f, i, k = 0, mid; printf("Enter the size array!\n"); scanf("%d", &size); printf("Enter the elements of array :\n "); for (i = 0; i < size; i++) { scanf("%d", &a[i]); } printf("Enter element to be searched:\n"); scanf("%d", &n); printf("Choose one of these option\n"); printf("1. Linear search\n"); printf("2. Binary search\n"); printf("Enter your choice:\n"); scanf("%d",&ch); int p= size - 1; switch (ch) { // for linear search case 1: for (i = 0; i < size; i++) { if (a[i] == n) { printf("Element found at %d position is %d", i + 1,n); f = 1; } } if (f != 1) printf("Element are not found\n"); break; case 2: // loop for binary search while (k <= p) { mid = (k + p) / 2; if (a[mid] == n) { f = 1; break; } else if (a[mid] > n) { p= mid - 1; } else { k = mid + 1; } } // while end if (f == 1) { printf("Element found at %d position is %d ", mid + 1,n); } else { printf("Element not found "); } break; default: printf(" Invalid choice "); break; } getch(); } Copy
Enter the size array! 5 Enter the elements of array : 22 4 8 10 13 Enter element to be searched: 8 Choose one of these option 1. Linear search 2. Binary search Enter your choice: 1 Element found at 3 position is 8 Copy
Enter the size array! 4 Enter the elements of array : 12 34 56 78 Enter element to be searched: 78 Choose one of these option 1. Linear search 2. Binary search Enter your choice: 2 Element found at 4 position is 78 Copy
0 Comments