Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Searching Techniques
- 4B. Write a program to search the element using sequential search.
- Search the element 10 and 100 in the following array using sequential search
- technique.
- 73,18,10,5,21,32,74
- #include <stdio.h>
- #include <conio.h> // Required for Turbo C functions
- int main() {
- int a[7] = {73, 18, 10, 5, 21, 32, 74}; // Array initialization
- int n = 7, i, data, found = 0;
- clrscr(); // Clear the screen for Turbo C
- // Display the array
- printf("Array A: ");
- for (i = 0; i < n; i++) {
- printf("%d ", a[i]);
- }
- // Prompt for the element to search
- printf("\nEnter the element to be searched: ");
- scanf("%d", &data);
- // Search for the element in the array
- for (i = 0; i < n; i++) {
- if (a[i] == data) {
- printf("The Element Is Present At %d Position!\n", i);
- found = 1;
- break; // Exit the loop as the element is found
- }
- }
- // If the element is not found
- if (!found) {
- printf("The Element Is Not Present In The Array!\n");
- }
- getch(); // Wait for a key press before exiting
- return 0;
- }
- 4C. Write a program to search the element using binary search.
- Search the element 250 in the following array using binary search technique.
- 10,20,25,51,75,100,250,500
- #include <stdio.h>
- #include <conio.h> // Required for Turbo C functions
- int main() {
- int a[8] = {10, 20, 25, 51, 75, 100, 250, 500}; // Sorted array
- int n = 8, data, i, lower_bound, upper_bound, mid;
- int found = 0; // Flag to indicate if the element is found
- clrscr(); // Clear the screen for Turbo C
- // Display the array
- printf("\nArray A: ");
- for (i = 0; i < n; i++) {
- printf("%d ", a[i]);
- }
- // Prompt for the element to search
- printf("\nEnter the element to be searched: ");
- scanf("%d", &data);
- lower_bound = 0;
- upper_bound = n - 1;
- // Binary search algorithm
- while (lower_bound <= upper_bound) {
- mid = (lower_bound + upper_bound) / 2;
- // Display the current bounds and middle position
- printf("\n\nStart = %d, End = %d, Mid = %d", lower_bound + 1, upper_bound + 1, mid + 1);
- if (data == a[mid]) {
- printf("\n\t%d = %d", data, a[mid]);
- printf("\nElement is present at position: %d", mid + 1);
- found = 1; // Mark as found
- break; // Exit the loop once the element is found
- } else if (data > a[mid]) {
- lower_bound = mid + 1; // Move to the right half
- printf("\n\t%d > %d, so move to RHS", data, a[mid]);
- } else {
- upper_bound = mid - 1; // Move to the left half
- printf("\n\t%d < %d, so move to LHS", data, a[mid]);
- }
- }
- // If the element is not found
- if (!found) {
- printf("\nThe element is not present in the array!");
- }
- getch(); // Wait for a key press before exiting
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement