Как указано выше, бинарный поиск предназначен для отсортированных данных. Ваш явно не отсортирован. Итак, прежде всего, вы должны отсортировать свои данные. Существует множество алгоритмов сортировки данных, но в приведенном ниже коде я использую быструю сортировку, которая также поможет вам понять ваш алгоритм поиска.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char ** a, char ** b) {
char * t = *a;
*a = *b;
*b = t;
}
/* This function takes last element as pivot, places
the pivot element at its correct position in sorted
array, and places all smaller (smaller than pivot)
to left of pivot and all greater elements to right
of pivot */
int partition (char ** arr, int low, int high) {
char * pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j <= high- 1; j++) {
// If current element is smaller than the pivot
if (strcmp(arr[j],pivot) < 0) {
i++; // increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
/* arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void quickSort(char **arr, int low, int high) {
if (low < high) {
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
int main(){
char *a = "abc";
char *b = "cdf";
swap(&a, &b);
printf("a = %s, b= %s\n", a, b);
char * data[10]={"cow", "goat", "dog", "sheep", "chicken", "duck", "bird","fish", "bee", "horse"};
quickSort(data, 0, 9);
for(int i = 0; i < 10; i++) {
printf("%s, ", data[i]);
}
return 0;
}
После сортировки вы можете использовать алгоритм поиска.