1. What are Algorithms?
An algorithm is nothing but a mention of steps to solve a problem. They are essentially a solution. Let's see the find the factorial of n.
Step1 : Initialize fact = 1
Step2 : For every value v in range 1 to n :
Multiply the fact by v
Step3 : fact contains the factorial of n
If we change algorithm into solution, our codes will be same as below :
def fcatorial(n):
fact = 1
for i in range(1,n):
fact = fact * i
return fact
Programming is all about data structures and algorithms. Data Structure are used to hold data while algorithms are used to solve the problem using that data.
2. Use of DSA to make our codes scalable
Two of the most valuable resources for a computer program are time and memory. The time taken by the computer to run code is : Time to run code = number of instructions * time to execute each instruction
The number of instructions dependes on the code we used, and the time taken the execute each code depends on our machine and complier.
# Non-optimized case
# Instructions
Initialize sum = 0
for every natural number n in range 1 to 1011(inclusive):
add n to sum
sum is your answer
# Codes
def findSum():
sum = 0
for i in range(1, 10000000000000000):
sum += i
return sum
# Optimized Case
# Instruction
Sum = N * (N + 1) / 2
# Codes
def findSum(N):
return N*(N + 1) / 2
Optimized code will execute in just one instruction and gets the task done no matter what the value is.
2.1 Scalability
Scalability means the quality of an algorithm/system to handle the problem of larger size. If we see our first solution to find the sum of first N natural numbers, it wasn't scalable. It's because it required linear growth in time with the linear growth in the size of the problem. Our second solution was very scalable and didn't require the use of any more time to solve a problem of larger size. These are known as constant-time algorithms.
2.2 Memory
Memory is not always available in abundance. While dealing with code/system which requires us to store a produce a lot of data, it is critical for our algorithm to save the usage of memory wherever possible.
'Course > [Progrmiz] Data Structure Algorithm' 카테고리의 다른 글
| [DS1] Stack (0) | 2022.08.10 |
|---|---|
| [Introduction] Divide and Conquer Algorithm (0) | 2022.08.09 |
| [Introduction] Asymptotic Notations (0) | 2022.08.08 |
| [Introduction] Data Structure and Types (0) | 2022.08.08 |
| [Introduction] What is algorithm? (0) | 2022.08.08 |