Untitled

 avatar
irfann
plain_text
6 months ago
1.2 kB
0
Indexable
Never
Sequential Search Program:

 #include <stdio.h>
int sequentialSearch(int arr[], int n, int key) {
 for (int i = 0; i < n; i++) {
 if (arr[i] == key)
 return i; // Key found, return the index
 }
 return -1; // Key not found
}
int main() {
 int arr[] = {64, 34, 25, 12, 22, 11, 90};
 int n = sizeof(arr)/sizeof(arr[0]);
 int key = 22;
 int index = sequentialSearch(arr, n, key);
 if (index != -1)
 printf("Element %d found at index %d\n", key, index);
 else
 printf("Element %d not found in the array\n", key);
 return 0;
}

Binary Search Program:

#include <stdio.h>
int binarySearch(int arr[], int left, int right, int key) {
 while (left <= right) {
 int mid = left + (right - left) / 2;
 if (arr[mid] == key)
 return mid;
 else if (arr[mid] < key)
 left = mid + 1;
 else
 right = mid - 1;
 }
 return -1; // Key not found
}
int main() {
 int arr[] = {11, 12, 22, 25, 34, 64, 90};
 int n = sizeof(arr)/sizeof(arr[0]);
 int key = 22;
 int index = binarySearch(arr, 0, n - 1, key);
 if (index != -1)
 printf("Element %d found at index %d\n", key, index);
 else
 printf("Element %d not found in the array\n", key);
 return 0;
}

Leave a Comment