Skip to content

Commit

Permalink
adding binary search
Browse files Browse the repository at this point in the history
  • Loading branch information
nkane committed Nov 17, 2018
1 parent bea7681 commit 00e0bac
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 2 deletions.
7 changes: 7 additions & 0 deletions algorithms/grokking-algorithms/binary_search/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
all: main

main:
clang src/main.c -I../ -o binary_search

clean:
rm binary_search
15 changes: 15 additions & 0 deletions algorithms/grokking-algorithms/binary_search/src/main.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#include <stdlib.h>
#include <lib/algorithms.c>

#define SIZE 100
#define FIND 99

int
main()
{
int *x = (int *)malloc(sizeof(int) * SIZE);
Generate_Array_Data_Int(x, len(x));
Binary_Search_Int(x, SIZE, FIND);
free(x);
return 0;
}
37 changes: 35 additions & 2 deletions algorithms/grokking-algorithms/lib/algorithms.c
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
#define global_variable

#define time_delta(t1, t2)((double)(t1 - t2)/CLOCKS_PER_SEC)
#define print_time(t)\
printf("Time: %f seconds\n", t)\

global_variable clock_t Start_Time;
global_variable clock_t End_Time;
Expand Down Expand Up @@ -41,8 +43,39 @@ Linear_Search_Int(int *buffer, int size, int search)
}
}
End_Time = clock();
Spent_Time = time_delta(End_Time,Start_Time);
printf("Time: %f seconds\n", Spent_Time);
Spent_Time = time_delta(End_Time, Start_Time);
print_time(Spent_Time);
return found;
}

int
Binary_Search_Int(int *buffer, int size, int search)
{
Start_Time = clock();
int found = 0;
int min = 0;
int max = size;
int mid = 0;
while (min != size)
{
mid = ((min + max) / 2);
if (mid == search)
{
found = 1;
break;
}
else if (search > mid)
{
min = mid;
}
else if (search < mid)
{
max = mid;
}
}
End_Time = clock();
Spent_Time = time_delta(End_Time, Start_Time);
print_time(Spent_Time);
return found;
}

Expand Down

0 comments on commit 00e0bac

Please sign in to comment.