#include "search.h"
#define USE_BINARY_SEARCH
int main() {
int array[] = {10, 8, 6, 4, 2, 0};
int array_length = sizeof(array) / sizeof(array[0]);
int key = 6;
#ifdef USE_BINARY_SEARCH
int key_position = search_binary(array, array_length, key);
#else
int key_position = search_linear(array, array_length, key);
#endif
printf("Pozitia cheii este: %d", key_position);
return 0;
}
#ifndef SEARCH_H
#define SEARCH_H
/* Implementare prin cautare liniara */
int search_linear(int array[], int array_length, int key) {
for(int i = 0; i < array_length; i++) {
if(array[i] == key) {
return i; // cheia a fost gasita, returneaza pozitia
}
}
return -1; // cheia nu a fost gasita in tablou
}
/* Implementare prin cautare binara */
int search_binary(int array[], int array_length, int key) {
int left_index = 0, right_index = array_length - 1;
while(left_index <= right_index) {
int middle_index = left_index + (right_index - left_index) / 2;
if(array[middle_index] == key) {
return middle_index; // cheia a fost gasita, returneaza pozitia
}
else if(array[middle_index] < key) {
right_index = middle_index - 1; // cheia se afla in partea stanga a tabloului
}
else {
left_index = middle_index + 1; // cheia se afla in partea dreapta a tabloului
}
}
return -1; // cheia nu a fost gasita in tablou
}
#endif /* SEARCH_H */