Skip to main content
Practice

What is an Algorithm?

Just as you need to follow a specific sequence and method to make a delicious dish, solving complex problems with a program requires clear procedures and rules.

An algorithm refers to a step-by-step procedure to solve a problem, much like a recipe for cooking.


Why Algorithms are Important in Programming

Algorithms are crucial because they determine the efficiency and accuracy of a program.

There can be various methods to solve a particular problem.

The key aspect of an algorithm is to find the optimal method that is faster and uses fewer resources among the potential solutions.


Types of Algorithms and Simple Code Examples

Algorithms can be categorized into various types based on their purpose and function.

In this lesson, we'll introduce several representative algorithms and examine simple code examples.


1. Search Algorithm

Search algorithms are methods to find specific values within data.

A basic example is the Linear Search.

Linear Search Example
def linear_search(arr, target):
# Iterate over the list length
for i in range(len(arr)):
# If the target value matches
if arr[i] == target:
# Return the index
return i
# Return -1 if no matching value is found
return -1

numbers = [3, 5, 2, 1, 10]
result = linear_search(numbers, 5)
print(result) # Output the index of 5, which is 1

The linear search algorithm sequentially searches from the start to the end of the list, and if it finds a matching target value, it returns the corresponding index.


2. Sorting Algorithm

Sorting algorithms arrange data in a certain order.

A basic sorting algorithm is the Bubble Sort.

Bubble Sort Example
# Bubble sort function
def bubble_sort(arr):
# Length of the list
n = len(arr)
# Iterate over the list length
for i in range(n):
# Iterate within the range reduced by i from the length
for j in range(0, n-i-1):
# If the current element is greater than the next element
if arr[j] > arr[j+1]:
# Swap the two elements' positions
arr[j], arr[j+1] = arr[j+1], arr[j]
# Return the sorted list
return arr

# List to be sorted
numbers = [64, 34, 25, 12, 22, 11, 90]

# Output the sorted list
print(bubble_sort(numbers))

The bubble sort algorithm sorts by comparing adjacent elements and repeating the process across the list until it is fully ordered.


3. Recursive Algorithm

Recursive algorithms solve a problem by breaking it down into smaller, more manageable problems.

A typical example is calculating the Fibonacci sequence.

Recursive Algorithm Example - Fibonacci Sequence
def fibonacci(n):
# If n is less than or equal to 1
if n <= 1:
return n
# If n is greater than or equal to 2
else:
# Return the sum of the (n-1)th and (n-2)th Fibonacci numbers
return fibonacci(n-1) + fibonacci(n-2)

result = fibonacci(6)

print(result) # Output 8

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.