DSA Week1
DSA Week1
Algorithms
Week-1
Sessional Work
• 2 Quizzes
• 4 Assignments
• Each Group Presentation
• Group Constraint(Not more than 5 students)
Warning
Consider it as FINAL NOTICE
Threat
• Don’t approach me for GPA.
Contents
Programming Language
• Just as you speak to a friend in a language so you
'speak' to the computer in a language. The only
language that the computer understands is called
binary.
• Binary is unfortunately very difficult for humans to
read or write so we have to use an intermediate
language and get it translated into binary for us.
Pre requisite programming concepts
Programming Language
Programming Language
• Surprisingly enough the thing that translates our
intermediate language into binary is also called
an interpreter.
• And just as you usually need a different
interpreter to translate English into Russian than
you do to translate Arabic into Russian so you
need a different computer interpreter to translate
Python into binary from the one that translates
VBScript into binary.
Pre requisite programming concepts
Assembler Programming
• This very simple improvement made life much
simpler and these systems of codes were really
the first programming languages, one for each
type of computer. They were known as
assembler languages and Assembler
programming is still used for a few specialized
programming tasks today.
• It was still very difficult and took a lot of
programming effort to achieve even simple tasks.
Pre requisite programming concepts
Points to remember
Points to remember
• Basically a programmer writes a program in a high
level language which is interpreted into binary that
the computer understands.
• In technical speak the programmer generates source
code and the interpreter generates object code.
Sometimes object code has other names like: binary
code or machine code.
Pre requisite programming concepts
Procedural Languages
• C, Pascal, FORTRAN, and similar languages
• Each statement in the language tells the computer to
do something
• Get some input,
• Add these numbers,
• Divide by six,
• Display that output.
• A program in a procedural language is a list of
instructions.
Pre requisite programming concepts
It consist of 6 phases
• Editor
• Preprocessor
• Compilers
• Linkers
• Loaders
• Execute
Pre requisite programming concepts
Program is created in the
Editor Disk editor and stored on disk.
Preprocessor program
Preprocessor Disk processes the code.
Compiler creates
Compiler Disk object code and stores
it on disk.
Linker Disk Linker links the object
code with the libraries
Primary Memory
Loader
Loader puts program
in memory.
Disk ..
..
..
Primary Memory
CPU takes each
CPU instruction and
executes it, possibly
storing new data
..
..
values as the program
..
executes.
Pre requisite programming concepts
Preprocessor Directives
• The first two lines that begin the program are preprocessor directives.
e.g., #include <iostream.h>
#include<conio.h>
• It isn’t a program statement
• It isn’t a part of a function body
• It does not end with a semicolon
Pre requisite programming concepts
Header Files
• iostream is an example of a header file.
• It’s concerned with basic input/output operations,
and contains declarations that are needed by the
cout identifier and the << operator.
• Without these declarations, the compiler won’t
recognize cout and will think << is being used
incorrectly
Pre requisite programming concepts
Functions
• The parentheses following the word main are the
distinguishing feature of a function.
• Without parentheses compiler would think that main
refers to some other program element.
• The word int preceding the function name indicates
that this particular function has a return value of
type int.
Pre requisite programming concepts
Program Statements
• There are three statements in the FIRST program: the line
• cout << “Hello World: My first C++ program”;
• getch();
• and the return statement return 0;
Pre requisite programming concepts
String Constants
• The phrase in quotation marks, “Hello World: My
first C++ program”, is an example of a string
constant.
• Its value is set when the program is written, and it
retains this value throughout the program’s
existence.
Pre requisite programming concepts
Program Statements
Program Statements
• getch() apart from holding the screen or waiting for a character to be
entered to exit the output screen , it also print the input given by the
user.
• The last statement in the function body is return 0;
• This tells main() to return the value 0 to whoever called it, in this case
the operating system or compiler. The value 0 indicates that the
program had terminated successfully.
Pre requisite programming concepts
Comments
• They help the person writing a program, and
anyone else who must read the source file,
understand what’s going on.
• The compiler ignores comments
Pre requisite programming concepts
Comment Syntax
• Comments start with a double slash symbol (//) and terminate at the
end of the line.
Pre requisite programming concepts
Outputs
Pre requisite programming concepts
Memory Concepts
• Variable names
• Correspond to actual locations in computer's memory
• Every variable has name, type, size and value
• When new value placed into variable, overwrites previous value
Increment Operators
• The ++ operator increments (adds 1 to) its argument.
• Normal way:
Arithmetic Operators
• Arithmetic calculations
• * : Multiplication
• / : Division
• Integer division truncates remainder
• 7 / 5 evaluates to 1
• % : Modulus operator returns remainder
• 7 % 5 evaluates to 2
46
Pre requisite programming concepts
Relational Operators
• A relational operator compares two values.
• The values can be any built-in C++ data type, such as char, int, and
float or they can be user-defined classes.
• The comparison involves such relationships as equal to, less than, and
greater than.
• The result of the comparison is true or false; for example, either two
values are equal (true), or they’re not (false).
Pre requisite programming concepts
Decision Making: Equality and Relational
Operators
Standard algebraic C++ equality Example Meaning of
equality operator or or relational of C++ C++ condition
relational operator operator condition
Relational operators
> > x > y x is greater than y
< < x < y x is less than y
Equality operators
= == x == y x is equal to y
!= x != y x is not equal to y
48
Pre requisite programming concepts
Example
Pre requisite programming concepts
OUTPUT
Pre requisite programming concepts
Example Expressions
Pre requisite programming concepts
Logical Operators
• Used as conditions in loops, if statements
• && (logical AND)
• true if both conditions are true
if ( gender == 1 && age >= 65 )
++seniorFemales;
• || (logical OR)
• true if either of condition is true
if ( semesterAverage >= 90 || finalExam >= 90 )
cout << "Student grade is A" << endl;
52
Pre requisite programming concepts
Logical Operators
• ! (logical NOT, logical negation)
• Returns true when its condition is false, & vice versa
if ( !( grade == sentinelValue ) )
cout << "The next grade is " << grade << endl;
Alternative:
if ( grade != sentinelValue )
cout << "The next grade is " << grade << endl;
53
Pre requisite programming concepts
Confusing Equality (==) and Assignment (=)
Operators
• Common error
• Does not typically cause syntax errors
• Aspects of problem
• Expressions that have a value can be used for decision
• Zero = false, nonzero = true
• Assignment statements produce a value (the value to be assigned)
54
Control Structures
• Sequential execution
• Statements executed in order
• Transfer of control
• Next statement executed not next one in sequence
• Structured programming – “goto”-less programming
• 3 control structures to build any program
• Sequence structure
• Programs executed sequentially by default
• Selection structures
• if, if/else, switch
• Repetition structures
• while, do/while, for
55
Pre requisite programming concepts
false true
grade >= 60
56
Pre requisite programming concepts
switch ( variable ) {
case value1: // taken if variable == value1
statements
break; // necessary to exit switch
case value2:
case value3: // taken if variable == value2 or == value3
statements
break;
Loops
• Loops cause a section of your program to be
repeated a certain number of times.
• The repetition continues while a condition is true a
certain number of times.
• When the condition becomes false, the loop ends and
control passes to the statements following the loop.
Pre requisite programming concepts
Kinds of Loop
• There are three kinds of loops in C++:
• for loop,
• while loop,
• do loop.
Pre requisite programming concepts
Pointers
• Variables used in a program can be considered as boxes that are
never empty.
• They are filled with some content either by the programmer or, if
uninitialized, by the operating system.
• A variable has at least two attributes: the content or value and the
location of the box or variable in computer memory.
• This content can be a number, a character, or a compound item such
as a structure or union.
• However, this content can also be the location of another variable;
variables with such contents are called pointers.
• Pointers are usually auxiliary variables that allow us to access the
values of other variables indirectly.
Pointers
Pre requisite programming concepts
int i=15,j,*p,*q;
i and j are numerical
variables and p and q are
pointers to numbers
Pre requisite concepts
• Primitive/Built-in Data types
int
char
boolean
string
float
long
double
Pre requisite concepts
Encapsulation
• Object-oriented programming (OOP) revolves around the concept of
an object.
• A class is a template in accordance to which objects are created.
• Information-hiding principle
Find Error????
Pre requisite concepts
Polymorphism
Polymorphism refers to the ability of acquiring many forms.
• Virtual Functions
• Function Overloading
Mid Term Examination
• Introduction to Data Structures and Algorithms;
• Complexity Analysis of Algorithms;
• Arrays;
• Sorting Algorithms: Insertion Sort, Selection Sort, Bubble Sort, Shell
Sort, Heap Sort, Quick Sort, Merge Sort, Radix Sort, Bucket Sort;
• Linked Lists: Singly Linked Lists, Doubly Linked Lists, Circular List;
• Stacks, Queues, and Priority Queue;
• Recursion: Function call and Recursion Implementation, Tail
Recursion, Non-tail Recursion, Indirect Recursion, Nested Recursion,
Backtracking.
PAPP
•Problem
•Algorithm
•Program
•Process
DATA STRUCTURE
Data Structure
A data structure is a data organization, management and storage
format that enables efficient access and modification.
Data structures help us to organize the data in the computer, resulting
in more efficient programs.
Examples:
Array, Lists, Stacks, Queue, Trees, Graphs
Need for Data Structures
Data structures organize data more efficient
programs.
More powerful computers more complex
applications.
More complex applications demand more
calculations.
Organizing Data
Any organization for a collection of records that
can be searched, processed in any order, or
modified.
The choice of data structure and algorithm can
make the difference between a program running
in a few seconds or many days.
Efficiency
A solution is said to be efficient if it solves the problem within its
resource constraints.
• Space
• Time
Linked list
queue
tree stack
Types of Data Structure
• Linear: In Linear data structure, values are arrange in linear
fashion.
• Array: Fixed-size
• Linked-list: Variable-size
• Stack: Add to top and remove from top
• Queue: Add to back and remove from front
• Priority queue: Add anywhere, remove the highest priority
Types of Data Structure
• Non-Linear: The data values in this structure are not arranged in
order.
• Hash tables: Unordered lists which use a ‘hash function’ to insert
and search
• Tree: Data is organized in branches.
• Graph: A more general branching structure, with less strict
connection conditions than for a tree
Type of Data Structures
• Homogenous: In this type of data structures, values of the same types of data are
stored.
• Array
• Data Structures
• Physical implementation of an ADT
• data structures used in implementations are provided in a language
(primitive or built-in) or are built from the language constructs (user-
defined)
• Each operation associated with the ADT is implemented by one
or more subroutines in the implementation
Abstract Data Type
• ADTs support abstraction, encapsulation, and information hiding.
• The principle of hiding the used data structure and to only provide a well-defined
interface is known as encapsulation.
The Core Operations of ADT
• Every Collection ADT should provide a way to:
• add an item
• remove an item
• find, retrieve, or access an item
• Traversing
• Searching
• Insertion
• Deletion
• Sorting
• Merging
Algorithms
• 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.
Algorithm: SUM(A, B)
• Algorithms resemble recipes. Recipes tell you how
to accomplish a task by performing a number of Step 1 - START
steps. For example, to bake a cake the steps are: Step 2 - C ← A + B + 10
preheat the oven; mix flour, sugar, and eggs Step 3 - Stop
thoroughly; pour into a baking pan; and so forth
• Algorithms are generally created independent of
underlying languages, i.e. an algorithm can be
implemented in more than one programming
language.
What is Pseudo Code ???
Categories of Algorithms
• 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.
Characteristics of an Algorithm
Not all procedures can be called an algorithm. An algorithm should have
the following characteristics −
• 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.
• Input − An algorithm should have 0 or more well-defined inputs.
• Output − An algorithm should have 1 or more well-defined outputs, and
should match the desired output.
• Finiteness − Algorithms must terminate after a finite number of steps.
• Feasibility − Should be feasible with the available resources.
• Independent − An algorithm should have step-by-step directions, which
should be independent of any programming code.
How to Write an Algorithm?
• There are no well-defined standards for writing algorithms. Rather, it
is problem and resource dependent. Algorithms are never written to
support a particular programming code.
• As we know that all programming languages share basic code
constructs like loops (do, for, while), flow-control (if-else), etc. These
common constructs can be used to write an algorithm.
• We write algorithms in a step-by-step manner, but it is not always the
case. Algorithm writing is a process and is executed after the problem
domain is well-defined. That is, we should know the problem domain,
for which we are designing a solution.
Arrays
• Array is a container which can hold a fix number of items and these items
should be of the same type. Most of the data structures make use of
arrays to implement their algorithms.
• Elementary data structure that exists as built-in in most programming
languages.
Arrays
Array declaration: int x[6];
An array is collection of cells of void main()
the same type. {
int x[6];
The collection has the name ‘x’. int j;
for(j=0; j < 6; j++)
The cells are numbered with {
consecutive integers. x[j] = 2*j;
cout<<x[j];
To access a cell, use the array }
}
name and an index:
x[0], x[1], x[2], x[3], x[4], x[5]
Arrays
x[0]
• Array cells are contiguous in x[1]
computer memory
x[2]
• The memory can be thought of as x[3]
an array.
x[4]
x[5]
Arrays
int x[6];
int n;
x[0] = 5;
x[1] = 2;
x = 3;// not allowed
x = a + b; // not allowed
x = &n; // not allowed
Array-Basic Operations
• Traverse − print all the array elements one by one.
• Insertion − Adds an element at the given index.
• Deletion − Deletes an element at the given index.
• Search − Searches an element using the given index or by the value.
• Update − Updates an element at the given index