Algorithms Chapter 1

2 Mins read

Hello! I said that ‘I’m presently reding a book about algorithms’, which is true! That book is just like a comic book named ‘grokking - algorithms’. The cover is mice. it’s real fun with my dad. You can try it with your parents. You can also try and explore yourself. You’ll soon find yourself becoming more and more familiar with stuff.

This chapter is easy for me, since I learnt Binary-Search before. But some things are new to me, such as the big O(Not 0) notation. I’ve never heard of it before! It’s fun, even if you know ‘Everything’, so I really recommand this book, and you can even record one video of it yourself!

 1# include <stdio.h>
 2int binary_search(int [], int, int); // Define function Binary Search
 3
 4int main(void)
 5{
 6    int my_list[] = {1, 3, 5, 7, 9}; // Define the list of values
 7    int len = sizeof(my_list) / sizeof(my_list[0]);
 8
 9    printf("%d\n", binary_search(my_list, 3, len)); // Binary search the list for 3
10    printf("%d\n", binary_search(my_list, 9, len)); // Binary search the list for 9
11    printf("%d\n", binary_search(my_list, 7, len)); // Binary search the list for 7
12    printf("%d\n", binary_search(my_list, -1, len)); // Binary search the list for -1
13
14    return 0;
15}
16
17int binary_search(int list[], int item, int len) // Write the code for Binary Search
18{
19    int low = 0; // First value
20    int high = len; // Last value
21
22    while (low <= high)
23    {
24        int mid = (low + high) / 2; // Middle value
25        int guess = list[mid]; // Make a guess for the middle value
26
27        if (guess == item) // So lucky
28        {
29            return mid; // Yeah! I've found it~
30        }
31        
32        else if (guess > item) // Too big. Not so lucky...
33        {
34            high = mid - 1; // Make the range smaller (Lower high)
35        }
36        else // Too small. No luck at all!
37        {
38            low = mid + 1; // Make the range smaller (Higher low)
39        }
40    }
41
42    return -9; // Sorry, the current value you're trying to find is not in this list!
43}