Unit1
Algorithm
• Algorithm is a step-by-step procedure, which defines a set of
instructions to be executed in a certain order to get the desired
output.
• Algorithms are generally created independent of underlying
languages, i.e. an algorithm can be implemented in more than one
programming language.
• From the data structure point of view, following are some important categories of algorithms
−
• Search − Algorithm to search an item in a data structure.
• Sort − Algorithm to sort items in a certain order.
• Insert − Algorithm to insert item in a data structure.
• Update − Algorithm to update an existing item in a data structure.
• Delete − Algorithm to delete an existing item from a data structure.
Algorithm example
• Two common approaches used in designing algorithms are the
bottom-up and top-down methods.
• Top-Down Approach
• The top-down approach, also known as “divide and conquer,” begins
by viewing the problem in its entirety.
• It starts with the main problem and breaks it down into smaller, more
manageable sub problems.
• This approach is generally associated with the use of recursion and is
prevalent in design techniques like dynamic programming and divide-
and-conquer algorithms.
• For example, in the case of a sorting problem like Merge Sort, a top-
down approach would start by splitting the entire array into smaller
pieces, sorting these smaller pieces, and then merging them back
together to create a sorted array.
• The bottom-up approach, on the other hand, starts with the simplest
and most basic subproblems and gradually builds up solutions to
larger subproblems.
• This technique is widely used in dynamic programming, where
solutions to subproblems are typically stored in a table for easy access
and to avoid recomputation.
• Take, for instance, the Fibonacci sequence, where each number is the
sum of the two preceding ones. A bottom-up algorithm would start by
computing the smallest values (base cases) of the sequence
Example 1: Write an algorithm to find the maximum of all the elements present in the
array.
Follow the algorithm approach as below:
Step 1: Start
Step 2: Declare a variable max with the value of the first element of the
array.
Step 3: Compare max with other elements using loop.
Step 4: If max < array element value, change max to new max.
Step 5: If no element is left, return or print max otherwise goto step 3.
Step 6: End
Example 2: Write an algorithm to find the average of 3 subjects.
• Step 1: Start
• Step 2: Declare and Read 3 Subject, let’s say S1, S2, S3
• Step 3: Calculate the sum of all the 3 Subject values and store result in
Sum variable (Sum = S1+S2+S3)
• Step 4: Divide Sum by 3 and assign it to Average variable.
• (Average = Sum/3)
• Step 5: Print the value of Average of 3 Subjects
• Step 6: End