Welcome to the exciting world of Logarithms! In this lesson, we'll explore how logarithms are a fundamental concept in Data Structures and Algorithms (DSA). Let's dive in! š³
Logarithms help us understand how fast or slow an algorithm operates. They're mathematical functions that relate multiplication to addition.
a is a base, and b is the value we want to find the logarithm of, we write it as log_a(b).a must be multiplied to get b.Let's take an example: log_2(8) = 3 because 2 multiplied by itself three times equals 8 (2 * 2 * 2 = 8).
Big O Notation is a popular way to describe the efficiency of an algorithm. It gives us the upper bound of time complexity in terms of logarithms.
n.Let's look at two simple examples:
Binary Search Algorithm: O(log n)
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2 # division with floor
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1 # not foundQuick Sort Algorithm: O(n log n)
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)What is the time complexity of the Binary Search Algorithm?
What is the time complexity of the Quick Sort Algorithm?
Congratulations on learning about logarithms in Data Structures and Algorithms! š
Stay tuned for more lessons on CodeYourCraft! If you have any questions, feel free to ask! š¬