You are on page 1of 22

W R I T T E N B Y

MICHELLE LAWSON

M S
IT H
OR LIES
G
AL THE GIR
FOR
What’s in this Book?
Introduction
Welcome Message
How to Use This Book

Getting Started with Algorithms


Understanding Algorithms
Algorithmic Thinking
Basic Elements of Algorithms

Sorting and Searching


Bubble Sort
Merge Sort
Quick Sort
Binary Search

Data Structures and Algorithms


Linking Data Structures with Algorithms
Arrays and List-Based Algorithms
Trees and Graphs in Algorithms

Graph Algorithms
Exploring Graphs
Dijkstra's Algorithm
Network Flow

Dynamic Programming
Understanding Overlapping Problems
Memoization
Algorithm Design Techniques
Divide and Conquer
Greedy Algorithms
Backtracking

Advanced Topics
Machine Learning Algorithms
Cryptographic Algorithms
Quantum Algorithms

Real-World Applications
Algorithms in Everyday Tech
Algorithms in Finance and Business

Final Thoughts and Encouragement


Empowering the Next Tech Girlies

Glossary

Further Resources
Books, websites, and online courses for
further learning.

About the Author


Introduction
Welcome Message
Hi there reader It's Michelle here, your go-to girly for all things
Computer Science I'm super excited to welcome you to "Algorithms
for the Girlies," a unique textbook that takes you on a journey into the
world of algorithms, spiced up with a dash of style and lots of fun
illustrations.

When I first dipped my toes into the world of computer science, I was
intrigued by how algorithms shape almost everything we do, yet I
found the resources a bit... dry. So I thought, "Why not add a bit of
sparkle to this?" This book is my attempt to blend the world of
algorithms with our everyday love for fashion and beauty, making it
not just informative but also relatable and fun! The relatability makes
it all easier to remember too.

Whether you're a budding Computer Science student, a tech


enthusiast, or just curious about how the digital world spins, this book
is for you. Let's decode the complex world of algorithms together,
with the same enthusiasm as we would for the latest Tiktok fashion
trend!

How to Use this Book


Algorithms for the Girlies" is designed to be your friendly guide
through the world of algorithms. Here's how to get the most out of it:

Take it One Step at a Time: Each chapter builds on the previous


one, so take your time to understand each concept before moving
on.
Embrace the Analogies: I use a lot of fashion and beauty analogies
to explain complex ideas. Embrace these to relate to the concepts
better.
Practice Makes Perfect: Try out the exercises and examples. You
learn a lot more from doing than just reading!
Reach Out: Got questions or just want to chat about an algorithm
that's caught your fancy? Reach out to me on Instagram
(@michellexcomputer) – I'm here to help.
Have Fun: Remember, learning something new should be fun and
exciting. Enjoy the journey as much as the destination!

So, grab your favorite drink, find a cozy spot, and let’s dive into the
stylish world of algorithms together. Let the adventure begin!
Getting Started With
Algorithms
Understanding Algorithms
An algorithm is simply a set of instructions. Like a makeup tutorial.

An algorithm, in the context of computer science and programming,


refers to a systematic approach to solving a particular problem or
accomplishing a specific task. It is essentially a step-by-step
procedure or a set of rules that guides the computer in carrying out
these tasks effectively. You can compare it to a carefully crafted
makeup tutorial that directs the computer on exactly what to do to
reach a desired outcome.

An algorithm takes in some input, like raw data or user input, and
through a series of calculations, comparisons, and logical operations,
produces a desired output.

These algorithms play a significant role in computer science, as they


enable programmers to develop efficient and reliable software. With
their help, complex problems can be broken down into smaller,
manageable parts, allowing for easier and more effective solutions.

The beauty of algorithms lies in their flexibility – they can be written in


various programming languages, from low-level ones like Assembly
or C to high-level ones such as Python or Java. Regardless of the
programming language used, the algorithm remains the same; only
the syntax may change. This adaptability allows programmers to
choose the most suitable language for their specific needs, without
having to reinvent the algorithm itself.
1
Algorithms are vital not only in computer science but also in various
other fields, such as mathematics, engineering, and commerce. Their
impact extends to everyday life, influencing the efficiency of search
engines, the optimization of routing systems, and even the
functionality of social media algorithms. They shape and uphold the
digital landscape we interact with on a daily basis.

Algorithms play a crucial role in programming for the following


reasons:

1. Problem Solving
Algorithms give us a systematic approach to solving problems. They
break down complex tasks into smaller, more manageable steps,
making it easier to apply efficient and effective solutions.

2. Efficiency and Performance


Well-designed algorithms can greatly improve the efficiency and
performance of a program. By carefully analyzing and optimizing
algorithms, programmers can reduce the time and memory resources
required to execute a task, resulting in faster and more responsive
software.

3. Reusability and Modularity


Algorithms can be designed to be modular and reusable. Once a
well-designed algorithm is implemented, it can be used in multiple
programs or parts of a program, saving time and effort in
development.

4. Scalability
Algorithms allow programs to handle larger and more complex
datasets or inputs. By utilizing efficient algorithms, programmers can
ensure that their software can scale and handle increased workloads
without sacrificing performance.

5. Correctness and Reliability


Well-defined algorithms provide a clear and unambiguous solution to
a problem. By following a proven algorithm, programmers can ensure
the correctness and reliability of their code, reducing errors and bugs.

2
Basically, algorithms are necessary tools for programming. They
enable programmers (that’s us ) to solve problems efficiently,
improve performance, make reusable code, handle scalability, and
ensure correctness and reliability. Understanding and implementing
algorithms is essential for any programmer seeking to develop high-
quality software. To do this, programmers learn to think
algorithmically. But, what does this even mean?

Algorithmic Thinking
The concept of algorithmic thinking is similar to that of
organizing and executing a beauty or fashion routine.
Just as developing a skincare routine involves
designing specific steps to achieve healthy, glassy
skin, algorithmic thinking involves breaking down a problem or
desired outcome into manageable steps to find an effective solution.
Let's explore this using our skin care routine analogy:

1. Identify the Goal

Just like setting a goal for your skin type (e.g., hydration, acne
treatment, anti-aging), in algorithmic thinking, the first step is to
clearly define the problem or objective you want to achieve with your
algorithm.

2. Gather Necessary Information

Think of this like assessing your skin type and concerns


before choosing products. In algorithms, this involves
gathering all relevant data and inputs that will affect the
outcome.

3. Decide on the Steps

Next, you plan your skincare routine step-by-step, considering the


order of products (cleanser, toner, moisturizer, etc.). This is much like
how you would design an algorithm, where you clearly define each
step, such that they follow a logical sequence.

3
4. Optimization

Just as you might choose a moisturizer with SPF to both hydrate and
protect from the sun, optimizing an algorithm involves finding the
most efficient way to achieve the goal with the least amount of
resources. We explore this further in following chapters - a lot of the
time, you’re trying to use less time and less space.

5. Testing & Adjustment

Trial and error in a beauty routine (like patch


testing a new product) is similar to testing an
algorithm. You check to see if you obtain desired
outcomes in various unique situuations and make
adjustments as needed.

6. Documentation and Sharing

Once you’ve designed your perfect


skincare routine, you might write it in
your journal and even share the
process on your social media pages.
Documenting and sharing your
algorithms allows other programmers
(and sometimes, your future self) to
understand, use and improve on
your method. Bob over here
did not clearly document his code.
Do not be like Bob!

7. Feedback

In beauty, feedback might come from seeing the results on your skin
or getting comments from others. In algorithms, feedback loops help
in refining and improving the algorithm based on the outcomes and
feedback. You can get feedback from professors, managers,
colleagues, and users. It is always important to make sure that these
stakeholders are considered when developing your algorithm.

This brings us to the end of our skin care routine development


process.
This process of breaking down problems into smaller, manageable
steps, and systematically solving them is known as Algorithmic
Thinking. It is with this method that you can approach and solve
many programming problems.

For example:

# You are given an array of integers


representing the scores of a class in
a math test.
# Your task is to sort the array in
descending order.

test_scores = [78, 92, 85, 60, 73, 88]


# Example array of test scores
sorted_scores = [92, 88, 85, 78, 73,
60]
# Example output

Identify the goal - Our goal is to sort a list of numbers in descending


order.

Gather Necessary Information - Understand the list of numbers or


data we need to sort. What data structure is it stored in? How is it
formatted?

Plan the steps - We can approach this with bubble sort, which
involves repeatedly stepping through the list, comparing adjacent
elements, and swapping them if they are in the wrong order. We talk
about this more in later chapters.

Optimize - We can optimize by stopping the algorithm if no swaps


are made in a new pass through the list, indicating that the list is
sorted.

Testing - Run the algorithm with different lists to ensure it correctly


sorts every time. Adjust if any errors are found.

5
Documentation - You can document your code by placing
comments in it to explain how each step contributes to our goal.

Feedback Loop - You can refine the algorithm based on


performance feedback, like how long it takes to execute for different
list sizes.

By following these steps, you can develop a systematic approach to


problem-solving that is methodical, efficient, and effective, much like
curating the perfect beauty routine. This approach can be used to
solve a variety of problems, especially programming problems.

Basic Elements of Algorithms


Now that we understand the concept of an algorithm, we're going to
delve into the core components of algorithms - loops, conditions, and
functions. Imagine we're accessorizing an outfit; each element can
add a special touch to complete the look. With practice, you begin to
learn when a particular element is needed. So, grab your fashionista
hat, and let's break it down with some fun, everyday analogies!

Loops

Think of loops like your daily outfit


routine. Every day, you go through your
wardrobe, picking out an outfit of the day
#OOTD. In programming, a loop is
similar.
A loop is a cycle that repeats a set of
instructions until a certain condition is
met, like how you keep choosing outfits
until you find the perfect one for the day.
When creating loops, it is important to know what our termination
condition is (the condition we have to meet before we stop). A loop
without a reachable termination condition is infinite… and that could
be very bad for a computer. Imagine searching for an outfit and never
ever stopping.

6
Conditions

Conditions in algorithms are like standing in front of your closet and


deciding if it's a sweater or a t-shirt kind of day. Based on the
weather (a condition), your choice changes.
In programming, conditions check for specific scenarios (like if it's
cold, wear a sweater) and make decisions on what the program
should do next.

Functions

Think of your skincare or makeup routine as an analogy for functions


in programming. In your beauty regimen, you have various products
such as a cleanser, toner, and moisturizer, each with a distinct
function - cleansing, refreshing, and hydrating your skin, respectively.
Similarly, in programming, functions are like these individual beauty
products.

A function is designed to perform a specific task or operation. Just as


you can use your beauty products either on their own or in
combination to create the perfect skincare routine, functions in
programming can be used independently or together to achieve a
specific outcome or to solve a particular problem in your code.

Now, let’s see how these elements work together in an algorithm:

7
# Example Python code

def find_perfect_outfit(temperature,
occasion):
"""
This function selects the perfect outfit
based on the temperature and the occasion.
It uses conditions to determine the
appropriate outfit.
"""

if temperature < 20:


outfit = "sweater"
else:
outfit = "t-shirt"

if occasion == "formal":
outfit += " and skirt"
else:
outfit += " and jeans"

return outfit

# Main program using a loop and the function


def main():
weekdays = ["Monday", "Tuesday",
"Wednesday", "Thursday", "Friday"]
for day in weekdays:
# For simplicity, let's assume the
temperature and occasion are the same for
all days
temperature = 18
occasion = "casual"

outfit =
find_perfect_outfit(temperature, occasion)
print(f"Outfit for {day}: {outfit}")

# Run the main program


main()
Functions:
The function find_perfect_outfit is defined to determine the
ideal outfit based on two parameters: temperature and
occasion.
Inside this function, conditions are used to select the outfit. If
the temperature is below 20 degrees, a sweater is chosen;
otherwise, a t-shirt. Further, depending on whether the
occasion is formal or casual, a skirt or jeans is added to the
outfit.
Loops:
The main function contains a loop that iterates over each day
of the week (represented by the list weekdays).
For each day, the find_perfect_outfit function is called with
a predefined temperature and occasion. This demonstrates
how the loop repeatedly executes the set of instructions (in
this case, choosing an outfit) for each item in the list.
Bringing It All Together:
The program runs the main function, where the loop goes
through each weekday and uses the find_perfect_outfit
function to determine the outfit.
The outcome for each day is printed, showing the chosen
outfit, which has been put together depending on whether or
not certain conditions were met by temperature and occasion.

This code shows us how loops, conditions, and functions are


fundamental elements in building algorithms. They allow for repetitive
tasks, decision-making based on criteria, and modularization of code
for specific tasks, respectively.

9
Exercise 1 - Getting Started
1.1 Define an Algorithm:

Write a short paragraph explaining what an algorithm is in your own


words. Use the analogy of a makeup tutorial to help illustrate your
explanation.

1.2 Identify Algorithm Components:

Consider a simple task like preparing a cup of coffee. Break down


this task into steps as if you were writing an algorithm. Highlight the
use of loops, conditions, and functions in your steps.

1.3 Optimization Challenge:

Given an algorithm that takes a list of numbers and returns the sum,
suggest a way to optimize this algorithm for better performance.
Think about the steps involved and where you might reduce the
number of operations.

1.4. Real-World Algorithm Application:

Identify a scenario in daily life where algorithms are used (other than
in computing or programming). Explain how algorithmic thinking is
applied in this scenario.

1.5 Create a Simple Algorithm:

Write a pseudo-code or a flowchart for a simple algorithm to decide


what to wear based on the weather. Your algorithm should include
conditions (e.g., if it's raining, choose a raincoat) and should aim to
reach a decision about an outfit.

10
Sorting & Searching
In this section, we're going to explore the world of sorting and
searching algorithms. Think of sorting as organizing your wardrobe to
make it both functional and fashionable. It's about putting things in
the right order, from your everyday jeans to your dazzling party
dresses, making it easier to find what you need, when you need it.

Sorting: The Art of Tidying Up Data


Sorting is all about arranging data neatly. Just like how you might
arrange your clothes by color, season, or style, sorting algorithms put
data in a specific order, be it numbers from low to high or names in
alphabetical order. This organization is essential for making data look
neat and easy to work with, just like a well-organized closet!

Searching: Finding Your Favorite


Pieces
On the flip side, searching is like
rummaging through your closet to find that
one perfect outfit for a special occasion. In
the world of programming, searching
algorithms help us quickly locate the data
we need in a large dataset, just like finding
your favorite scarf or that one pair of
earrings that completes your look.

As we dive into this section, we'll uncover various sorting and


searching techniques, understand their unique styles, and see how
we can make these processes more efficient - faster and less space-
consuming. We’re all about making our algorithms functional - a skill
every chic programmer should have in their repertoire!

11
Bubble Sort
The first sorting algorithm we must explore is Bubble Sort. Now,
Bubble Sort might not be the fastest method out there (think of it as
the leisurely stroll of sorting), but it's a classic and a great way to get
to grips with sorting principles.

How Bubble Sort Works:

The Basics:
Imagine you're going through your collection of party dresses, aiming
to arrange them from the shortest to the longest. You start by
comparing two pairs at a time, swapping their places if the one on the
left is longer than the one on the right. Repeat this comparison and
swap process, and soon, you'll have your dresses lined up perfectly!
This is the fundamental idea of bubble sort.

Illustration by Potturi Reshma

The Approach:

Start at one end of your array (just like you would start at one end of
your dress rack).

Compare each pair of adjacent elements.

If they're in the wrong order (say, the dress on the left is longer than
the dress on the right), swap them.
12
Repeat this process, moving through the array like you’re shuffling
through your shades, until every item is in its fabulous place.

With each complete pass through the array, the item with the highest
value (in our case, the longest dress) ends up in its correct position.

After a maximum of n - 1 passes through any array with n elements,


we would have completely sorted the array.

Here’s why:

In the first pass, the largest element 'bubbles up' to its correct
position at the end of the array.

In the second pass, the second-largest element moves to its


correct position (just before the largest element), and so on.

With each subsequent pass, fewer elements need to be


compared because the largest elements are already sorted at the
end of the array.

By the time you've done n - 1 passes, all elements are in their


correct positions, as there is no need to perform a pass for the
last remaining unsorted element (it will already be in its correct
position after the (n-1)th pass).

So, in the worst-case scenario (where the array is in reverse order


and requires full sorting), Bubble Sort would require n - 1 passes
through the array. This shows hat bubble sort is a linear time
algorithm - in the worst case scenario, the number of steps it takes to
complete the algorithm is directly proportional to the amount of
elements in the array. Believe it or not, that’s not very fast.

Why Bubble Sort?

Bubble Sort is your go-to for smaller, manageable sorting tasks. It's
like choosing an outfit for a casual day out – simple and reliable.
While it may not be the quickest, it's a great starting point for
understanding basic sorting algorithms.
13
Bubble Sort in Action

Let’s run a Bubble Sort on a hypothetical list of accessory prices.


We'll sort them in ascending order, from budget-friendly to splurge-
worthy.

Here’s a snippet of what that might look like in Python:

def bubble_sort(accessory_prices):
n = len(accessory_prices) # Get the
number of items in the array
for i in range(n): # Outer loop
for j in range(0, n-i-1): # Inner
loop to compare adjacent elements
# If current element is greater than
the next, swap them
if accessory_prices[j] >
accessory_prices[j+1]:
accessory_prices[j],
accessory_prices[j+1] = accessory_prices[j+1],
accessory_prices[j] # Swapping

return accessory_prices
# Return the sorted array

In this code, we're moving through our list of accessory prices.

We compare each price with the next one and swap them if they're in
the wrong order, and this is how we bubble sort. Remember, we
simply keep comparing and swapping items within little bubbles.

14
Exercise 2 - Bubble Sort
1.1 Bubble Sort in Practice:

Given a list of numbers: [34, 12, 45, 32, 10, 6], apply the Bubble Sort
algorithm to sort the list in ascending order. Write down each step of
the process, showing how you compare and swap elements in the
list, just like you would organize accessories by their style or size.

1.2 Identify the Most Efficient Pass:

Consider an already sorted list: [5, 9, 12, 18, 22, 30]. If you apply
Bubble Sort to this list, how many passes will it take to confirm that
the list is already sorted? Explain your answer by describing what
happens during each pass through the list.

1.3 Comparing Sorting Techniques:

Imagine you have a large wardrobe with a variety of clothing items


mixed up. If Bubble Sort were a method of organizing your wardrobe,
how would it differ from a method where you first group clothes by
type (dresses, trousers, tops), then sort each group individually?
Explain how these two methods relate to different sorting algorithms
in terms of efficiency and practicality.

14
Merge Sort
Merge Sort is an efficient, comparison-based, divide and conquer
sorting algorithm. Fundamentally, it works by dividing the unsorted
list into n sublists, each containing one element (a list of one element
is considered sorted), then repeatedly merging these sublists to
produce new sorted sublists until there is only one sublist remaining.
This final sublist is the sorted list.

How Merge Sort Works:

Divide: Imagine you're faced


with the daunting task of
organizing a huge, mixed pile of
clothes. Instead of tackling it all
in one go, you split it into
smaller, more manageable piles.
Similarly, Merge Sort begins by
dividing the array into two
halves.

Conquer: With your clothes now


in smaller piles, you sort each
pile individually, much like
sorting socks by color or shirts
by style. In Merge Sort, this step
involves recursively sorting the
Source: GeeksforGeeks two halves that were created.

Merge: Once each section is neatly organized, you start combining


them back together, ensuring they maintain their order. You might
merge your sorted socks with your shirts, arranging them by type or
color in your drawers. Merge Sort does the same by merging the two
sorted halves into a single, sorted sequence.

Repeat: This process is repeated, with the


array being split, sorted, and merged,
until you end up with a single, fully
organized pile - or in Merge Sort's case,
a fully sorted array.
... you have reached the end of the free sample. :(

If you would like to read the rest of this textbook, you can get the full
version here.

Lots of love,
Michelle. <3

You might also like