diff --git a/source_codes/complexity/.gitignore b/source_codes/complexity/.gitignore index 7878686d5c5f4b1d1f8feb2a82f2c7292aa670c1..549fd57861fb4e0be32e3d50caf2081e36ac50b7 100644 --- a/source_codes/complexity/.gitignore +++ b/source_codes/complexity/.gitignore @@ -1,6 +1,2 @@ +search sum -sum_one -sum_one_opt -sum_thousand -sum_thousand_opt - diff --git a/source_codes/complexity/search.c b/source_codes/complexity/search.c new file mode 100644 index 0000000000000000000000000000000000000000..395cc7380b08ab5b5445f251d49fd1d38206edc1 --- /dev/null +++ b/source_codes/complexity/search.c @@ -0,0 +1,62 @@ +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include <time.h> + +#define SIZE 1000 + +void init(int n, int tab[]) { + for (int i = 0; i < n; ++i) { + tab[i] = 3 * i; + printf("%d ", tab[i]); + } + printf("\n"); +} + +bool is_present_linear(int n, int tab[], int elem, int *steps) { + *steps = -1; + for (int i = 0; i < n; ++i) { + *steps = i; + if (tab[i] == elem) { + return true; + } else if (elem < tab[i]) { + return false; + } + } + return false; +} + +bool is_present_binary_search(int n, int tab[], int elem, int *steps) { + *steps = 0; + int left = 0; + int right = n - 1; + while (left <= right) { + *steps += 1; + int mid = (right + left) / 2; + if (tab[mid] < elem) { + left = mid + 1; + } else if (tab[mid] > elem) { + right = mid - 1; + } else { + return true; + } + } + return false; +} + +int main() { + srand(time(NULL)); + int tab[SIZE]; + init(SIZE, tab); // we should init randomly and sort but... I'm lazy + int elem = rand() % (4 * SIZE); + int steps = 0; + bool is_present = is_present_linear(SIZE, tab, elem, &steps); + printf("Condition %d is present is %s in %d steps\n", elem, + is_present ? "true" : "false", steps); + bool is_present_b = is_present_binary_search(SIZE, tab, elem, &steps); + printf("Condition %d is present is %s in %d steps\n", elem, + is_present_b ? "true" : "false", steps); + + return EXIT_SUCCESS; +} +