From ffa1b6ee736ab1947c0a18606bc520a78142ad7d Mon Sep 17 00:00:00 2001
From: Orestis <orestis.malaspinas@pm.me>
Date: Wed, 27 Oct 2021 12:16:34 +0200
Subject: [PATCH] added code for find complexity

---
 source_codes/complexity/.gitignore |  6 +--
 source_codes/complexity/search.c   | 62 ++++++++++++++++++++++++++++++
 2 files changed, 63 insertions(+), 5 deletions(-)
 create mode 100644 source_codes/complexity/search.c

diff --git a/source_codes/complexity/.gitignore b/source_codes/complexity/.gitignore
index 7878686..549fd57 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 0000000..395cc73
--- /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;
+}
+
-- 
GitLab