Skip to content
Snippets Groups Projects
Verified Commit ffa1b6ee authored by orestis.malaspin's avatar orestis.malaspin
Browse files

added code for find complexity

parent bd350f28
No related branches found
No related tags found
No related merge requests found
search
sum
sum_one
sum_one_opt
sum_thousand
sum_thousand_opt
#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;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment