0% found this document useful (0 votes)
20 views18 pages

Inbound 6215576121251288497

Uploaded by

sudeepimag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views18 pages

Inbound 6215576121251288497

Uploaded by

sudeepimag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

1

STD : XII SUBJECT : COMPUTER SCIENCE


Lesson - 1 Function
UNIT- I
Problem Solving Lesson - 2 Data Abstraction
Techniques Lesson - 3 Scoping
Lesson - 4 Algorithmic Strategies
Lesson - 1 FUNCTION
Part - II
Answer the following questions: (2 Marks)
1. What is a subroutine?
Subroutines are the basic building blocks of computer programs. Subroutines are small sections of
code that are used to perform a particular task that can be used repeatedly. In Programming
languages these subroutines are called as Functions.
2. Define Function with respect to Programming language.
A function is a unit of code that is often defined within a greater code structure. Specifically, a
function contains a set of code that works on many kinds of inputs, like variants, expressions and
produces a concrete output.
3. Write the inference you get from X :=(78).
X :=(78) has an expression in it but (78) is not itself an expression. Rather, it is a function
definition. Definitions bind values to names, in this case the value 78 being bound to the name ‘X’.
4. Differentiate interface and implementation.
Interface Implementation
 Interface just defines what an object  Implementation carries out the instructions
can do, but won’t actually do it. defined in the interface.
 In object oriented programs classes  In object oriented programs how the object
are the interface is processed and executed is the
implementation.
5. Which of the following is a normal function definition and which is recursive function definition
(i) let sum x y: normal function definition
return x + y
(ii) let disp : normal function definition
print ‘welcome’
(iii) let rec sum num: recursive function definition
if (num!=0) then return num + sum (num-1)
else
return num
Part - III
Answer the following questions: (3 Marks)
1. Mention the characteristics of Interface.
 The class template specifies the interfaces to enable an object to be created and operated properly.
 An object's attributes and behaviour is controlled by sending functions to the object.
2. Why strlen() is called pure function?
strlen() is a pure function because the function takes one variable as a parameter, and accesses it
to find its length. This function reads external memory but does not change it, and the value
returned derives from the external memory accessed.
3. What is the side effect of impure function? Give example.
Function has side effects when it has observable interaction with the outside world.
One of the most popular groups of side effects is modifying the variable outside of function.
The side effect is not a necessary bad thing. Sometimes they are useful.
Example:
y: = 0
let inc (int) x:=
y: = y + x;
return (y)
2

Here, the result of inc( ) function change every time if the value of ‘y’ get changes inside the
function definition. Hence the side effect of inc( ) function is changing the data of the external
visible variable ‘y’.
4. Differentiate pure and impure function.
pure function impure function
 A function can be a pure function  The variables used inside the function may
provided it should not have any cause side effects though the functions
external variable which will alter the which are not passed with any arguments. In
behaviour of that variable. such cases the function is called impure
function
 The return value of the pure functions  The return value of the impure functions
solely depends on its arguments does not solely depend on its arguments
passed. Hence, if we call the pure passed. Hence, if we call the impure functions
functions with the same set of with the same set of arguments, we might get
arguments, we will always get the the different return values
same return values.
 They do not have any side effects.  They may have side effects.
 They do not modify the arguments  They may modify the arguments which are
which are passed to them passed to them
 Example:  Example:
let square x:= let Randomnumber:=
return x * x a := random()
if a > 10 then
return: a
else
return: 10
 Here, the function ‘square’ is a pure  Here the function ‘Randomnumber’ is
function because it will not give different impure as it is not sure what will be the result
results for same input. when we call the function.
5. What happens if you modify a variable outside the function? Give an example.
One of the most popular groups of side effects is modifying the variable outside of function.
Example:
y: = 0
let inc (int) x:=
y: = y + x;
return (y)
Here, the result of inc( ) function change everytime if the value of ‘y’ get changes inside the function
definition. Hence the side effect of inc( ) function is changing the data of the external visible variable ‘y’.
Part - IV
Answer the following questions (5Marks)
1. What are called Parameters and write note on (i) Parameter without Type (ii) Parameter with Type
Parameters are the variables in a function definition and arguments are the values which are passed
to a function definition.
Parameter without Type:
(requires: b>=0 )
(returns: a to the power of b)
let rec pow a b:=
if b=0 then 1
else a * pow a (b-1)
In the above function definition we have not mentioned any types. Some language compiler solves
this type inference problem algorithmically, but some require the type to be mentioned.
Parameter with Type:
(requires: b> 0 )
(returns: a to the power of b )
let rec pow (a: int) (b: int) : int :=
if b=0 then 1
else a * pow a (b-1)
When we write the type annotations for ‘a’ and ‘b’ the parentheses are mandatory. There are times
we may want to explicitly write down types. This is useful on times when you get a type error from
the compiler. Explicitly annotating the types can help with debugging such an error message.
3

2. Identify in the following program


let rec gcd a b :=
if b <> 0 then gcd b (a mod b) else return a
i) Name of the function - gcd
ii) Identify the statement which tells it is a recursive function - rec
iii) Name of the argument variable - a,b
iv) Statement which invoke the function recursively - gcd b (a mod b)
v) Statement which terminates the recursion - return a
3. Explain with example Pure and impure functions.
pure function impure function
 A function can be a pure function  The variables used inside the function may
provided it should not have any cause side effects though the functions
external variable which will alter the which are not passed with any arguments. In
behaviour of that variable. such cases the function is called impure
function
 The return value of the pure functions  The return value of the impure functions
solely depends on its arguments does not solely depend on its arguments
passed. Hence, if we call the pure passed. Hence, if we call the impure functions
functions with the same set of with the same set of arguments, we might get
arguments, we will always get the the different return values
same return values.
 They do not have any side effects.  They may have side effects.
 They do not modify the arguments  They may modify the arguments which are
which are passed to them passed to them
 Example:  Example:
let square x:= let Randomnumber:=
return x * x a := random()
if a > 10 then
return: a
else
return: 10
 Here, the function ‘square’ is a pure  Here the function ‘Randomnumber’ is
function because it will not give different impure as it is not sure what will be the result
results for same input. when we call the function.

4. Explain with an example interface and implementation.


Interface and Implementation:
 Interface just defines what an object can do, but won’t actually do it.
 In object oriented programs classes are the interface.
 Implementation carries out the instructions defined in the interface (i.e) the code that carries
out the behaviour.
 In object oriented programs how the object is processed and executed is the implementation.
 A class declaration combines the external interface with an implementation of that interface.
An object is an instance created from the class. The interface defines an object’s visibility to
the outside world.
For example, let's take the example of increasing a car’s speed:
 The person who drives the car doesn't care about the internal working. To increase the speed
of the car he just presses the accelerator to get the desired behaviour. Here the accelerator is
the interface between the driver and the engine.
 Internally, the engine of the car is doing all the things. It's where fuel, air, pressure, and
electricity come together to create the power to move the vehicle, this is called
implementation.
4

5. Chameleons of Chromeland problem using function:


 Let us represent the number of chameleons of each type by variables a, b and c, and their
initial values by A, B and C, respectively.
 Let a = b be the input property.
 The input – output relation is a = b = 0 and c = A + B + C.
 Let us name the algorithm monochromatize. The algorithm can be specified as
monochromatize (a, b, c)
--inputs: a=A, b=B, c=C, a=b
--outputs: a=b=0, c=A + B + C
while a>0
a,b,c=a-1,b-1,c+2

In each iterative step, two chameleons of the two types (equal in number) meet and change
their colors to the third one. (i.e) In each meeting, a and b each decreases by 1, and c
increases by 2. For example, if A, B, C = 4, 4, 6, then the series of meeting will result in:

The solution can be expressed as an iterative algorithm using function.


let rec monochromatize a b c :=
if a > 0 then
a, b, c := a-1, b-1, c+2
monochromatize a b c
else
return c
5

Lesson - 2 DATA ABSTRACTION


Part - II
Answer the following questions: (2 Marks)
1. What is abstract data type?
Abstract Data type (ADT) is a type for objects whose behavior is defined by a set of value and a
set of operations. The definition of ADT only mentions what operations are to be performed but
not how these operations will be implemented. In abstract data type the representation of a data
type is unknown.
2. Differentiate constructors and selectors.
constructors selectors
Constructors are functions that build the Selectors are functions that retrieve
abstract data type. information from the data type.
Example: Example:
getname(city)
city = makecity (name, lat, lon) getlat(city)
getlon(city)
In the above example the function In the above example the function
makecity (name, lat, lon) is the constructor getname(city), getlat(city) , getlon(city)
which creates the object city. are the selectors because these
functions extract the information of the
city object
3. What is a Pair? Give an example.
Any way of bundling two values together into one can be considered as a pair. Lists are a common
method to do so. Therefore List can be called as Pairs.
Example: x:= [10, 20]
x[(0, 10), (1, 20)] - where
(0, 10) (1, 20)

Index position value


4. What is a List? Give an example.
List is constructed by placing expressions within square brackets separated by commas. Such an
expression is called a list literal. List can store multiple values. Each value can be of any type and
can even be another list. Example: x: = [10, 20]
5. What is a Tuple? Give an example.
A tuple is a comma-separated sequence of values surrounded with parentheses. We cannot
change the elements of a tuple once it is assigned Example: x: = (10, 20)

Part - III
Answer the following questions: (3 Marks)
1. Differentiate Concrete data type and abstract datatype.
Concrete data type abstract datatype
Concrete data types or structures are Abstract Data type (ADT) is a type for
direct implementations of a relatively objects whose behavior is defined by a
simple concept. set of value and a set of operations. It
offers a high level view of a concept
independent of its implementation.
A concrete data type is a data type whose In abstract data type the representation
representation is known. of a data type is unknown
6

2. Which strategy is used for program designing? Define that Strategy.


“Wishful thinking” is a powerful strategy for designing programs.
Wishful Thinking is the formation of beliefs and making decisions according to what might be
pleasing to imagine instead of by appealing to reality.
3. Identify which of the following are constructors and selectors?
(a) N1=number() - Constructor
(b) accetnum(n1) - Selector
(c) displaynum(n1) - Selector
(d) eval(a/b) - Selector
(e) x,y= makeslope (m), makeslope(n) - Constructor
(f) display() - Selector
4. What are the different ways to access the elements of a list? Give example.
The elements of a list can be accessed in two ways.
The first way is via multiple assignments, which unpacks a list into its elements and binds each
element to a different name.
Example: x: = [10, 20]
a, b:=x
The second method is by the element selection operator, which selects an element from the value
of the preceding expression.
Example: x: = [10, 20]
a: = x[0]
b: = x[1]
5. Identify which of the following are List, Tuple and class?
(a)arr [1, 2, 34] - List
(b) arr (1, 2, 34) - Tuple
(c) student [rno, name, mark] - Class
(d) day= (‘sun’, ‘mon’, ‘tue’, ‘wed’) - Tuple
(e) x= [2, 5, 6.5, [5, 6], 8.2] - List
(f) employee [eno, ename, esal, eaddress] - Class
Part - IV
Answer the following questions (5Marks)
1. How will you facilitate data abstraction? Explain it with suitable example
To facilitate data abstraction, we will need to create two types of functions: constructors and
selectors.
Constructors:
Constructors are functions that build the abstract data type. For example, Assume an abstract
data type called city. This city object will hold the city’s name, and its latitude and longitude. To
create a city object, we would use a function like
Example: city = makecity (name, lat, lon)
In the above example the function makecity (name, lat, lon) is the constructor which creates the
object city.
7

Selectors:
Selectors are functions that retrieve information from the data type. To extract the information
of a city object, we would use functions like
Example:
getname(city)
getlat(city)
getlon(city)
In the above example the function getname (city), getlat (city), getlon (city) are the selectors
because these functions extract the information of the city object

Example:
The following pseudo code will compute the distance between two city objects:
distance(city1, city2):
lt1, lg1 := getlat(city1), getlon(city1)
lt2, lg2 := getlat(city2), getlon(city2)
1/2
return ((lt1 - lt2)**2 + (lg1 - lg2)**2))
In the above code:
Read distance(), getlat() and getlon() as functions
Read lt as latitude and lg longitude.
Read := as “assigned as” or “becomes”
lt1, lg1 := getlat(city1), getlon(city1)
Read as lt1 becomes the value of getlat(city1) and lg1 becomes the value of getlont(city1).
2. What is a List? Why List can be called as Pairs. Explain with suitable example
List is constructed by placing expressions within square brackets separated by commas. Such an
expression is called a list literal. List can store multiple values. Each value can be of any type and
can even be another list. Example: x: = [10, 20]
The elements of a list can be accessed in two ways.
The first way is via multiple assignments, which unpacks a list into its elements and binds each
element to a different name.
Example:
x: = [10, 20]
a, b:=x
The second method is by the element selection operator, which selects an element from the
value of the preceding expression.
Example:
x: = [10, 20]
a: = x[0]
b: = x[1]
Any way of bundling two values together into one can be considered as a pair. Lists are a common
method to do so. Therefore List can be called as Pairs.
Example: x:= [10, 20]
x[(0, 10), (1, 20)] - where
(0, 10) (1, 20)

Index position value


8

3. How will you access the multi-item? Explain with example.


To represent multi-item, we can use structure construct also called class construct in OOP language,
where each part is named. For example consider a person datatype where each 'item' is a named
thing: the firstName, the lastName, the id, and the email.
Example:
class Person:
creation( )
firstName := " "
lastName := " "
id := " "
email := " "
The new data type Person is pictorially represented as:

Let main( ) contains


p1:=Person() Statement creates the object.
firstName := " Padmashri " setting a value for firstName field
lastName := "Baskar" setting a value for lastName field
id := "994-222-1234" setting a value for id field
email="compsci@gmail.com" setting a value for email field
- - output of firstName : Padmashri
9

Lesson - 3 SCOPING
Part - II
Answer the following questions: (2 Marks)
1. What is a scope?
Scope refers to the visibility of variables, parameters and functions in one part of a program to
another part of the same program.
2. Why scope should be used for variable. State the reason.
 Scope defines the order in which variables have to be mapped to the object in order to obtain
the value.
 It is a good practice to limit a variable's scope to a single definition. This way, changes inside
the function can't affect the variable on the outside of the function in unexpected ways.
3. What is mapping?
The process of binding a variable name with an object is called mapping. = (equal to sign) is used
in programming languages to map the variable and object.
4. What do you mean by Namespaces?
Namespaces are containers for mapping names of variables to objects. we can consider
namespace as dictionaries, containing list of words and its meanings. The words are mapped with
its meaning in dictionaries whereas names are mapped with objects (name : = object) in
programming language. Example: a:=5
5. How Python represents the private and protected Access specifiers?
Python prescribes a convention of prefixing the name of the variable or method with single or
double underscores to emulate the behaviour of protected and private access specifiers.
All members in a Python class are public by default. Any member can be accessed from outside
the class environment in Python
Part - III
Answer the following questions: (3 Marks)
1. Define Local scope with an example.
Local scope refers to variables defined in current function.
Always, a function will first look up for a variable name in its local scope.
Only if it does not find it there, the outer scopes are checked.
Example: Output:
Disp( ):
a:=7 Local Scope 7
print(a)
Disp( )

2. Define Global scope with an example.


A variable which is declared outside of all the functions in a program is known as global
variable. This means, global variable can be accessed inside or outside of all the functions in a
program.
Example: Output:
a=10 Global Scope
Disp( ): 7
10
a:=7 Local Scope
print(a)
Disp( )
print(a)
10

3. Define Enclosed scope with an example.


A variable which is declared inside a function which contains another function definition with in
it, the inner function can also access the variable of the outer function. This scope is called
enclosed scope
Example: Output:
Disp1( ):
b:=3 Enclosed scope 3
Disp2( ):
print b
Disp2( )
Disp1()

4. Why access control is required?


Access control is a security technique that regulates who or what can view or use resources in a
computing environment. It is a fundamental concept in security that minimizes risk to the object.
In other words access control is a selective restriction of access to data.
5. Identify the scope of the variables in the following pseudo code and write its output

color:= Red global scope Output: Red Blue Green


mycolor(): Red Blue
b:=Blue enclosed scope Red
myfavcolor():
g:=Green local scope
print color, b, g
myfavcolor()
print color, b
mycolor()
print color
Part - IV
Answer the following questions (5Marks)
1. Explain the types of scopes for variable or LEGB rule with example.
The LEGB rule is used to decide the order in which the scopes are to be searched for scope
resolution. There are 4 types of Variable Scope. These scopes are listed below in terms of
hierarchy (highest to lowest).
 Local(L)
 Enclosed(E)
 Global(G
 Built-in (B)
Local Scope:
Local scope refers to variables defined in current function.
Always, a function will first look up for a variable name in its local scope. Only if it does not find it there,
the outer scopes are checked.
Example: Output:
Disp( ):
a:=7 Local Scope 7
print(a)
Disp( )
11

Global Scope:
A variable which is declared outside of all the functions in a program is known as global variable.
This means, global variable can be accessed inside or outside of all the functions in a program.
Example: Output:
a=10 Global Scope
Disp( ): 7
10
a:=7 Local Scope
print(a)
Disp( )
print(a)

Enclosed Scope:
A variable which is declared inside a function which contains another function definition with in it,
the inner function can also access the variable of the outer function. This scope is called enclosed
scope.
Example: Output:

Disp( ): 10
a:=10 Enclosed scope 10
Disp1( ):
print a
Disp1( )
print a
Disp()

Built-in Scope:
The built-in scope has all the names that are pre-loaded into the program scope when we start
the compiler or interpreter. Any variable or module which is defined in the library functions of a
programming language has Built-in or module scope. They are loaded as soon as the library files
are imported to the program.
Example:
Built-in/module scope Library files associated with the software
Disp( ):
a:=10
Disp1( ):
print a
Disp1( )
print a
Disp()

2. Write any Five Characteristics of Modules.


Characteristics of Modules:
1. Modules contain instructions, processing logic, and data.
2. Modules can be separately compiled and stored in a library.
3. Modules can be included in a program.
4. Module segments can be used by invoking a name and some parameters.
5. Module segments can be used by other modules.
3. Write any five benefits in using modular programming.
The benefits of using modular programming:
 Less code to be written.
 The code is stored across multiple files.
 Code is short, simple and easy to understand.
 Errors can easily be identified, as they are localized to a subroutine or function.
 The same code can be used in many applications.
 The scoping of variables can easily be controlled.
12

Module:
A module is a part of a program. A single module can contain one or more statements closely
related each other. Modules can be integrated with other modules.
Modular Programming:
The process of subdividing a computer program into separate sub-programs is called Modular
programming. Modular programming enables programmers to divide up the work and debug pieces
of the program independently. The examples of modules are procedures, subroutines, and
functions.
13

Lesson - 4 Algorithmic Strategies


Part - II
Answer the following questions: (2 Marks)
1. What is an Algorithm?
An algorithm is a finite set of instructions to accomplish a particular task. It is a step-by-step
procedure for solving a given problem. An algorithm can be implemented in any suitable
programming language.
2. Define Pseudo code.
Pseudo code is a detailed description of what a computer program or algorithm must do. It is
normally expressed in a natural language rather than in a programming language.
In other words it is an informal way of representing a program in high level language; it does not
follow any strict rules or syntax. It is for understanding purpose only.
3. Who is an Algorist?
A person who is skilled in design of Algorithm is called Algorist.
4. What is sorting?
To sort items in a certain order using the methods such as bubble sort, insertion sort, selection
sort, etc.
5. What is searching? Write its types.
To search an item in a data structure using linear and binary search.
Searching is a process of finding a data in a data structure. There are two types of searching
methods. They are: linear search and binary search.
Part - III
Answer the following questions: (3 Marks)
1. List the characteristics of an algorithm.
An algorithm should have the following characteristics:
Input, Output, Finiteness, Definiteness, Effectiveness, Correctness, Simplicity, Unambiguous,
Feasibility, portable, Independent.
2. Discuss about Algorithmic complexity and its types.
Computer resources are limited. Efficiency of an algorithm is defined by the utilization of time
and space complexity. Suppose A is an algorithm and n is the size of input data, the time and
space used by the algorithm A are the two main factors, which decide the efficiency of A.
The complexity of an algorithm f (n) gives the running time and/or the storage space required by
the algorithm, where n is the size of input data.
Time Complexity:
The Time complexity of an algorithm is given by the number of steps taken by the algorithm to
complete the process.
Space Complexity:
Space complexity of an algorithm is the amount of memory required to run to its completion.
3. What are the factors that influence time and space complexity.
Computer resources are limited. Efficiency of an algorithm is defined by the utilization of time
and space complexity. Suppose ‘A’ is an algorithm and ‘n’ is the size of input data, the time and
space used by the algorithm ‘A’ are the two main factors, which decide the efficiency of ‘A’.
Time Factor -Time is measured by counting the number of key operations like comparisons in the
sorting algorithm.
Space Factor - Space is measured by the maximum memory space required by the algorithm.
14

4. Write a note on asymptotic notation.


Asymptotic Notations are languages that use meaningful statements about time and space
complexity. The following three asymptotic notations are mostly used to represent time
complexity of algorithms:
(i) Big O: Big O is used to describe the worst-case of an algorithm.
(ii) Big Ω: Big Omega is the reverse Big O; Big Omega is used to describe the lower bound
(best-case) of an algorithm.
(iii) Big Θ: When an algorithm has a complexity with lower bound = upper bound, say that an
algorithm has a complexity O (n log n) and Ω (n log n), it’s actually has the complexity
Θ (n log n), which means the running time of that algorithm always falls in n log n in
the best-case and worst-case.
5. What do you understand by Dynamic programming?
 Dynamic programming is an algorithmic design method that can be used when the solution to
a problem can be viewed as the result of a sequence of decisions.
 Dynamic programming approach is similar to divide and conquer. The given problem is divided
into smaller and yet smaller possible sub-problems, so that their results can be re-used to
complete the process.
 Dynamic programming approaches are used to find the solution in optimized way. For every
inner sub problem, dynamic algorithm will try to check the results of the previously solved
sub-problems. The solutions of overlapped sub-problems are combined in order to get the
better solution.
Part - IV
Answer the following questions (5Marks)
1. Explain the characteristics of an algorithm.
An algorithm should have the following characteristics:
Input Zero or more quantities to be supplied.
Output At least one quantity is produced.
Finiteness Algorithms must terminate after finite number of steps.
All operations should be well defined. For example operations involving
Definiteness division by zero or taking square root for negative number are
unacceptable.
Effectiveness Every instruction must be carried out effectively.
Correctness The algorithms should be error free.
Simplicity Easy to implement.
Unambiguous Algorithm should be clear and unambiguous. Each of its steps and their
inputs/outputs should be clear and must lead to only one meaning.
Feasibility Should be feasible with the available resources.
portable An algorithm should be generic, independent of any programming language
or an operating system able to handle all range of inputs.
Independent An algorithm should have step-by-step directions, which should
be independent of any programming code.
2. Discuss about Linear search algorithm.
Linear search also called sequential search is a sequential method for finding a particular value in
a list. This method checks the search element with each element in sequence until the desired
element is found or the list is exhausted. In this searching algorithm, list need not be ordered.
Pseudo code
Step-1: Traverse the array using for loop.
Step-2: Compare the search element with the current value of the list.
Step-3: If the values match, display the current index and value of the array If the values do not
match, move on to the next array element. If no match is found, display the search
element not found.
Example:x[ ] = {5,34,65,12,77,35}
index: 0 1 2 3 4 5
elements: 5 34 65 12 77 35

target = 77
Output: 4 Element found
15

3. What is Binary search? Discuss with example.


Binary search also called half-interval search algorithm. It finds the position of a search element
within a sorted array.
Pseudo code:
Step-1: Find the index of middle element.
Step-2: Compare the search element with middle element:
 if the values match, return the index of middle element with success message.
 If search element is greater than middle element, now change the low value as mid + 1, then
repeat step 1.
 If search element is less than middle element, now change the high value as mid - 1, then
repeat step 1.
Step-3: If search element is not in the list, then return unsuccessful message.
Example: x[ ] = {5,12,34,35,65,77}
index: 0 1 2 3 4 5
elements: 5 12 34 35 65 77
target = 77
Output: 5 Element found
4. Explain the Bubble sort algorithm with example.
Bubble sort is a simple sorting algorithm. The algorithm starts at the beginning of the list of values
stored in an array. It compares each pair of adjacent elements and swaps them if they are in the
unsorted order. This comparison and passed to be continued until no swaps are needed, although
the algorithm is simple, it is too slow and less efficient when compared to insertion sort and other
sorting methods.
Pseudo code:
Step-1: Start with the first element i.e., index = 0, compare the current element with the next
element of the array.
Step-2: If the current element is greater than the next element of the array, swap them.
Step-3: If the current element is less than the next element, move to the next array element.
Go to Step 1 and repeat until end of the index is reached.
Example: Let's consider an array with values {15,11,16,12,14,13} Below, we have a
pictorial representation of how bubble sort will sort the given array.

15 11 16 12 14 13
Step (1): 15 > 11 So interchange

11 15 16 12 14 13

Step (2): 15 < 16 No swapping 11 15 16 12 14 13

11 15 16 12 14 13
Step (3): 16 > 12 So interchange

11 15 12 16 14 13

11 15 12 16 14 13
Step (4): 16 > 14 So interchange

11 15 12 14 16 13

11 15 12 14 16 13
Step (5): 16 > 13 So interchange

11 15 12 14 13 16
16

Step (6): 11 < 15 No swapping 11 15 12 14 13 16

11 15 12 14 13 16
Step (7): 15 > 12 So interchange
11 12 15 14 13 16

11 12 15 14 13 16
Step (8): 15 > 14 So interchange

11 12 14 15 13 16

11 12 14 15 13 16
Step (9): 15 > 13 So interchange

11 12 14 13 15 16

Step (10): 15 < 16 No swapping 11 12 14 13 15 16

Step (11): 11 < 12 No swapping 11 12 14 13 15 16

Step (12): 12 < 14 No swapping 11 12 14 13 15 16

11 12 14 13 15 16
Step (13): 14 > 13 So interchange

11 12 13 14 15 16

At the end of all the iterations we will get the sorted values in an array {11,12,13,14,15,16}

5. Explain the concept of Dynamic programming with suitable example.


 Dynamic programming is an algorithmic design method that can be used when the solution to
a problem can be viewed as the result of a sequence of decisions.
 Dynamic programming approach is similar to divide and conquer. The given problem is divided
into smaller and yet smaller possible sub-problems, so that their results can be re-used to
complete the process.
 Dynamic programming approaches are used to find the solution in optimized way. For every
inner sub problem, dynamic algorithm will try to check the results of the previously solved
sub-problems. The solutions of overlapped sub-problems are combined in order to get the
better solution.
Steps to do Dynamic programming
1. The given problem will be divided into smaller overlapping sub-problems.
2. An optimum solution for the given problem can be achieved by using result of smaller sub-problem.
3. Dynamic algorithms use Memoization. It is an optimization technique used to speed up
computer programs by storing the previously calculated values.
Example - Fibonacci Iterative Algorithm with Dynamic programming approach
Initialize f0=0, f1 =1
Step-1: Print the initial values of Fibonacci f0 and f1
Step-2: Calculate Fibonacci fib ← f0 + f1
Step-3: Assign f0← f1, f1← fib
Step-4: Print the next consecutive value of Fibonacci fib
Step-5: Goto step-2 and repeat until the specified number of terms generated
For example if we generate Fibonacci series up to 5 digits, the algorithm will generate the series
as shown below: The Fibonacci series is : 0 1 1 2 3
17

6. Explain the Selection sort algorithm with example.


The selection sort is a simple sorting algorithm that improves on the performance of bubble sort
by making only one exchange for every pass through the list. This algorithm will first find the
smallest elements in array and swap it with the element in the first position of an array, then it
will find the second smallest element and swap that element with the element in the second
position, and it will continue until the entire array is sorted in respective order. This algorithm
repeatedly selects the next-smallest element and swaps in into the right place for every pass.
Hence it is called selection sort.
Pseudo code:
Step-1: Search the smallest element in the array, and swap it with the element in the first position.
Step-2: Now we look for smallest element present in the sub-array, from starting index to till the last
index of sub - array.
Step-3: Now replace the second smallest identified in step-2 at second position in the original array.
Step-4: This is repeated, until the array is completely sorted.
Example: Let's consider an array with values {13, 16, 11, 18, 14, 15}
Initial At the end of At the end of At the end of At the end of At the end of
array First pass Second pass Third pass Fourth pass Fifth pass
13 11 11 11 11 11
16 16 13 13 13 13
11 13 16 14 14 14
18 18 18 18 15 15
14 14 14 16 16 16
15 15 15 15 18 18
Finally we will get the sorted array end of the pass
7. Explain the Insertion sort algorithm with example.
Insertion sort is a simple sorting algorithm. It works by taking elements from the list one by one
and inserting then in their correct position in to a new sorted list. This algorithm builds the final
sorted array at the end.
Pseudo code:
Step-1: If it is the first element, it is already sorted.
Step-2: Pick next element.
Step-3: Compare with all elements in the sorted sub-list.
Step-4: Shift all the elements in the sorted sub-list that is greater than the value to be sorted.
Step-5: Insert the value.
Step-6: Repeat until list is sorted.
Example: Let's consider an array with values {44, 16, 83, 07, 67, 21, 34, 45, 10}
44 16 83 07 67 21 34 45 10
16 44 83 07 67 21 34 45 10
16 44 83 07 67 21 34 45 10
07 16 44 83 67 21 34 45 10
07 16 44 67 83 21 34 45 10
07 16 21 44 67 83 34 45 10
07 16 21 34 44 67 83 45 10
07 16 21 34 44 45 67 83 10
07 10 16 21 34 44 45 67 83
18

1. What is algorithmic solution?


An algorithm that yields expected output for a valid input is called an algorithmic solution.
2. Differentiate Algorithm and program:
Algorithm Program
Algorithm helps to solve a given problem Program is an expression of algorithm in a
logically and it can be contrasted with the programming language
program
Algorithm can be categorized based on Algorithm can be implemented by
their implementation methods, design structured or object oriented programming
techniques etc approach
There is no specific rules for algorithm Program should be written for the selected
writing but some guidelines should be language with specific syntax
followed.
Algorithm resembles a pseudo code which Program is more specific to a programming
can be implemented in any language language

3. Write notes on analysis of algorithm:


Analysis of algorithms and performance evaluation can be divided into two different phases:
1. A Priori estimates: This is a theoretical performance analysis of an algorithm. Efficiency
of an algorithm is measured by assuming the external factors.
2. A Posteriori testing: This is called performance measurement. In this analysis, actual
statistics like running time and required for the algorithm
executions are collected.

Algorithm Complexity:
Complexity Worst Best Average
Linear O(n) O(1) O(n)
Search method Binary O(log n) O(1) O(log n)
Bubble sort (stable) O(n2) Ω(n) Ѳ(n2)
Insertion sort (stable) O(n2) Ω(n) Ѳ (n2)
Selection sort O(n2) Ω(n2) Ѳ (n2)
Sort method Quick sort O(n2) Ω (n log n) Ѳ (n log n)
Merge sort (stable) O(n log n) Ω (n log n) Ѳ (n log n)
Heap sort O(n log n) Ω (n log n) Ѳ (n log n)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy