Algorithms Chapter 1
@ Mr. Eric | Friday, Aug 20, 2021 | 2 minute read | Update at Friday, Aug 20, 2021

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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# include <stdio.h>
int binary_search(int [], int, int); // Define function Binary Search

int main(void)
{
    int my_list[] = {1, 3, 5, 7, 9}; // Define the list of values
    int len = sizeof(my_list) / sizeof(my_list[0]);

    printf("%d\n", binary_search(my_list, 3, len)); // Binary search the list for 3
    printf("%d\n", binary_search(my_list, 9, len)); // Binary search the list for 9
    printf("%d\n", binary_search(my_list, 7, len)); // Binary search the list for 7
    printf("%d\n", binary_search(my_list, -1, len)); // Binary search the list for -1

    return 0;
}

int binary_search(int list[], int item, int len) // Write the code for Binary Search
{
    int low = 0; // First value
    int high = len; // Last value

    while (low <= high)
    {
        int mid = (low + high) / 2; // Middle value
        int guess = list[mid]; // Make a guess for the middle value

        if (guess == item) // So lucky
        {
            return mid; // Yeah! I've found it~
        }
        
        else if (guess > item) // Too big. Not so lucky...
        {
            high = mid - 1; // Make the range smaller (Lower high)
        }
        else // Too small. No luck at all!
        {
            low = mid + 1; // Make the range smaller (Higher low)
        }
    }

    return -9; // Sorry, the current value you're trying to find is not in this list!
}
Mr. Eric
Life writes the best stories. Let’s study together! Never copy please!
A Friendly Introduction to Number Theory Algebra Ii Algebra Problem Algorithm Code Euclid Geometry Germination Method Number Theory Opinion Poetry Appreciation Reflection Seed Solve Speech Stop Motion

© 2020 - 2023 Mr. Eric

Powered by Hugo with theme Dream.

Mr. Eric

I am a student, learn, happy.

Always happy.