FDS Unit I
FDS Unit I
Solution
Algorithm
Data Structure
Program
Data Structure Terms
• Data: Data are simply collection of facts and figures. Data are
values or set of values.
int mark[5];
Static and Dynamic Data Structure
• Dynamic data structure is a data structure in which one can
allocate memory as per the requirement. If one does not want
to use some block of memory, we can deallocate it.
• E.g. Linked List
class Node:
# constructor
def __init__(self, data, next=None):
self.data = data
self.next = next
10 20 10 30 20 10
(a) (b) (c)
30 20
Algorithms
Problem Solving
Here are six steps for problem solving
Select the
Step 1 Understan Step 3 best Step 5 Evaluate
d the List the solution to List the the
problem. possible the Instruction solution.
Identify the problem.
problem. solution to s using the
the selected
Step 2 problem. Step 4 solution. Step 6
Problem Solving- Example
Example : Let us take a very simple example of an algorithm which adds the two
numbers and store the result in a third variable.
Step 1 : Start.
Step 2 : Read the first number is variable ‘a’
Step 3 : Reed the second number in variable ‘b’
Step 4 : Perform the addition of both the numbers ie. and store the result in
variable ‘c’
Step 5 : Print the value of ‘c’ as a result of addition.
Step 6 : Stop.
Characteristics of Algorithm
1. Unambiguous − Algorithm should be clear and unambiguous. Each of its
steps (or phases), and their inputs/outputs should be clear and must lead to
only one meaning.
2. Input − An algorithm should have 0 or more well-defined inputs.
3. Output − An algorithm should have 1 or more well-defined outputs, and
should match the desired output.
4. Finiteness − Algorithms must terminate after a finite number of steps.
5. Feasibility − Should be feasible with the available resources.
6. Independent − An algorithm should have step-by-step directions, which
should be independent of any programming code.
Algorithm Design Tools
There are various ways by which we can specify an algorithm.
• Pseudo code
This representation of algorithm is mix of programming
language and natural language.
• Flowchart
As name suggested these are charts or diagrams which
represent the flow of the algorithm.
Psudocode
Definition : Pseudo code is nothing but an informal way of writing a program. It is a
combination of algorithm written in simple English and some programming language.
• In pseudo code, there is no restriction of following the syntax of the
programming language.
• Pseudo codes cannot be compiled. It is just a previous step of developing a
code for given algorithm.
• Even sometimes by examining the pseudo code one can decide which
language has to select for implementation.
• The algorithm is broadly divided into two sections as follows
Algorithm heading
It consist of name of algorithm, problem description,
input and output
Algorithm body
It consist of logical body of the algorithm by making use
of various programming constructs and assignment
statement
Structure of algorithm
Rules for Writing an Algorithm
let us understand some rules for writing the algorithm.
1. Algorithm is a procedure consisting of heading and body. The heading
consists of keyword Algorithm and name of the algorithm and parameter
list. The syntax is
Algorithm name (p1,p2,…………..pn)
//Problem description :
//Input :
//Output :
3. Then body of an algorithm is written, in which various programming constructs
like if, for, while or some assignment statements may be written.
4. The compound statements should be enclosed within { and } brackets.
5. Single line comments are written using // as beginning of comment.
6. The Identifier should begin by letter and not by digit. An identifier can be a
combination of alphanumeric string.
7. Using assignment operator < an assignment statement can be given.
For instance : Variable expression
8. There are other types of operators such as Boolean operators such as true or
false. Logical operators such as and, or, not And relational operators such as <,
<=, >, >=, =, ≠
9. The array indices are stored with in square bracket [ ] . The index of array usually
start at zero. The multidimensional arrays can also be used in algorithm.
10. The inputting and outputting can be done using read and write
For example:
11. The conditional statement such as if-then or if-then-else are written in following
form:
if (condition) then statement
if (condition) then statement else statement
for i ← 1 to n step 1
Here variable i is
{
incremented by 1 at
write (i)
each iteration
}
14. The repeat – until statement can be written as :
repeat
statement 1
statement 2
.
.
statement n
until (condition)
15. The break statement is used to exit from inner loop. The return statement is
used to return control from one point to another.
Note that statements in an algorithm executes in sequential order i.e in the same
order as they appear-one after another.
Sub-Algorithm
A sub-algorithm is complete and independently defined algorithmic module.
This module is actually called by some main algorithm or some another sub –
algorithm.
Que: What do you mean by flow chart? Give the meaning of each
symbol used in flowchart. Draw flowchart to compute the sum of
elements from a given integer array.
SPPU: May-10, Marks-8
Examples
Design and explain an algorithm to find the sum of the digits of an integer
number.
SPPU Dec-10, Marks-6
Read N
Remainder = 0
Sum = 0
Repeat
Remainder = N mod 10
Sum = Sum + Remainder
N = N/10
Until N < 0
Display Sum
End
Examples
What is the difference between flowchart and algorithm? Convert the
algorithm for computing factorial of given number into flowchart.
SPPU May-11, Marks-8
Read N
Set i and F to 1
While i < = N
F=F*i
increase the value of i by 1
Display F
End
Analysis of Algorithm
For Example : Consider following code for counting the frequency count
def fun () :
a = 10 …………………………………….1
print(a)…………………………………….1
def fun () :
a = 0 …………………………………….1
for i in range (1, n)……………………….n + 1
a = a + i………………………...n
print (a)…………………………………...1
To compute the space complexity we use two factors: constant and instance
characteristics. The space requirement S(p) can be given as
S(p) = C + Sp
• Where C is a constant i.e. fixed part and it denotes the space of inputs and
outputs.
• This space is an amount of space taken by instruction, variables and identifiers.
• And Sp is space dependent upon instance characteristics.
• This is a variable part whose space requirement depends on particular problem
instance.
Continue…
Space Complexity
There are two types of components that contribute to the space
complexity – Fixed part and variable part
For determining the time complexity of particular algorithm following steps are
carried out -
Continue…
Example
Write an algorithm to find smallest element in a array of integers and
analyze its time complexity SPPU-May-13, Marks-8
} Total 2n+3
Write (min_element)
}
• Let, n0 and constant c are two integers such that n0 denotes some value of
input and n > n0. Similarly c is some constant such that c > 0. We can
write
f(n) <= c*g(n)
Solution:
Solution:
Note: The theta notation is more precise with both big oh and omega notation.
Some Example of Asymptotic Notation
mergeSort(arr[], l, r)
if r > 1
1. Find the middle point to divide the array into two sub lists:
middle m = (l + r) /2
2. Call mergeSort for first half:
Call mergeSort (arr, l, m)
3. Call mergeSort for second half:
Call mergeSort (arr, m+1, r)
4. Merge the two sub-lists sorted in step 2 and 3 :
Call merge (arr, l, m, r)
Example: Merge Sort
• The following diagram shows complete merge sort process for an
example array {38,27,43,3,9,82,10}.
• The array is recursively divided in two lists till the size becomes 1.
• Once the size becomes 1, the merge process comes into action and starts
merging array back till the complete array is merged.
# Pseudo Code
Algorithm mergeSort (arr, l, r)
// Problem Description : This algorithm is for sorting the
// elements using merge sort
// Input: Array arr of unsorted elements, l as beginning (left side)
// pointer of array arr and r as end pointer of array (right side)
// Sorted array arr[0……n-1]
if (l < r) then
{
mid ← (l + r) / 2 //split the list at mid
mergeSort (arr, l, r) // First sublist
mergeSort (arr, mid+1, r) // Second sublist
Combine (arr, l, mid, r) //merging of two sublists
}
Algorithm Combine (arr, l, mid, r)
{
k←l // k as index for array temp
i←l // i as index for left sublist of array arr
j ← mid + 1 // j as index for right sublist of array arr
while (i <= mid and j <= r) do
{
if (arr [i] <= arr [j])then // if smaller element is present in left sublist
{
temp [k] ← arr [i]
i←i+1
k←k+1
}
else //smaller element is present in right sublist
{
// copy smaller element to temp array
temp [k] ← arr [j]
i←i+1
k←k+1
}
}
// copy remaining elements of left sublist to temp
while (i <= mid) do
{
temp [k] ← arr [i]
i←i+1
k←k+1
}
// copy remaining elements of right sublist to temp
while (j <= r) do
{
temp [k] ← arr [j]
i←i+1
k←k+1
}
Time complexity of Merge Sort is O(nLogn) in all 3 cases (worst, average and best)
as merge sort always divides the array into two halves and take linear time to merge
two halves.
# Python program for implementation of MergeSort
def mergeSort(arr):
if len(arr) >1:
mid = len(arr)//2 # Finding the mid of the array
L = arr[:mid] # Dividing the array elements
R = arr[mid:] # into 2 halves
i=j=k=0
A C E
8 3
Continue…
Example of Greedy Strategy
• Now we will consider each vertex as a source and will find the shortest
distance from this vertex to every other remaining vertex.
Source
Distance with other vertices Path shown in graph
Vertex
A-B, path = 4
A-C, path = 8
A
A-D, path = ∞
A-E, path = ∞
B-C, path = 4 + 1
B B-D, path = 4 + 3
B-E, path = ∞
C-D, path = 5+7 = 12
C
C-E, path = 5+3 = 8
D D-E, path = 7+8 = 15
• But we have one shortest distance obtained from A to E and that is A-B-
C-E with path length = 4+1+3 = 8. Similarly other shortest paths can be
obtained by choosing appropriate source and destination.
Pseudo Code
Time Complexity of the implementation is O(V2).
Assignment No.1
1. Define and explain the following terms :
(i) Data (ii) Data structure (iii) Flowchart.
2. Define algorithms and explain its characteristics.
3. Explain the divide and conquer strategy with suitable example.
Comment on its time complexity.
4. Explain the Asymptotic notation Big O, Omega and Theta with
suitable example.
5. Explain static and dynamic data structures with examples.
6. Differentiate between linear and non-linear data structure with
example.
7. Explain the Greedy strategy with suitable example. Comment on its
time complexity.
8. Define and explain ADT(Abstract Data Type).
9. State Analysis of programming constructs - Linear, Quadratic, Cubic,
Logarithmic
10. Define and explain the following terms : (a) Persistent data structure
(b) Ephemeral data structure (c) Time complexity (d) Space complexity
Case Study