You are on page 1of 36

CHAPTER ONE

INTRODUCTION TO DATA STRUCTURES


AND ALGORITHMS
 PROGRAM
 ALGORITHM
 DATA STRUCTURE
 ARRAY
 FUNCTION
 POINTER
Data structure
• The way data are organized in a computers memory .
• Is a representation of data and the operations allowed
on that data
are the method of representing of logical relationships
between individual data elements related to the
solution of a given problem.
conceptual and concrete ways to organize data for
efficient storage and efficient manipulation

2
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
• Non-Linear: The data values in this structure are not
arranged in order.
Tree: Data is organized in branches.
Graph: A more general branching structure, with less
strict connection conditions than for a tree 3
SOME TERMINOLOGIES

Entity: an entity is something, that has certain attributes


which may be assigned values
Field: a single elementary unit of information
representing an attribute of an entity
Record: collection of field values of a given entity
File: collections of records of the entities in a given
entity set
Data Structure operations
Data in the data structures are processed by means of
certain operations.

4
Some of the most frequently used operations are:

Searching: finding the location of the record with


a given key value
Inserting: adding a new record to the structure
Deleting: removing the record from the structure
Sorting: arranging the records in some logical
order (e.g., alphabetically)
Merging: combining the records of two different
sorted files into a single sorted file
Two or more operations may be used in a given situation
• E.g., to delete a specific record, one needs to first
search, and then perform delete operation
5
Algorithm
sequence of computational steps to solve a problem
An algorithm is a procedure for solving a problem in finite
number of steps
Algorithm is a well defined computational procedure that
takes some value (s) as input, and produces some value (s)
as output.
Algorithm is finite number of computational statements
that transform input into the output
An Algorithm is said to be accurate and truthful only when
it provides the exact wanted output.

6
• Data structures model the static part of the world. They are
unchanging while the world is changing.
• In order to model the dynamic part of the world we need to
work with algorithms.
• Algorithms are the dynamic part of a program’s world
model.
• An algorithm transforms data structures from one state to
another state in two ways:
An algorithm may change the value held by a data
structure.
An algorithm may change the data structure itself.
• The quality of a data structure is related to its ability to
successfully model the characteristics of the world.
• Similarly, the quality of an algorithm is related to its ability
to successfully simulate the changes in the world.
• However, the quality of data structure and algorithms is
determined by their ability to work together well.
• Generally speaking, correct data structures lead to simple
and efficient algorithms.
• And correct algorithms lead to accurate and efficient data
structures. An algorithm may be given in different forms.
• A description using English/other languages
• A real computer program, e.g. C++
• A pseudo-code, C-like program, program-language-like
program.
Properties of Algorithms
Finiteness:
 Algorithm must complete after a finite number of steps.
 Algorithm should have a finite number of
steps.
Finite  int i=0; Infinite while(true){
while(i>10){ cout<<“Hello”;
cout<< i; }
i++;
}
SEQUENTIAL
Each step must have a unique defined preceding and
succeeding step.
 The first step (start step) and last step (halt step) must be
clearly noted.
Feasibility:
 It must be possible to perform each instruction.
 Each instruction should have possibility to
be executed.
1) if(5>7) {
cout<<“hello”; // not executed before.
}
Correctness:
It must compute accurate/right answer for all possible legal
inputs.
The output should be as expected and required and correct.
Language Independence:
 It must not depend on any one programming language.
Completeness:
 It must solve the problem totally/absolutly.
Effectiveness:
It should be easy to understand and to perform tracing.
 The steps of logical execution are well organized.
Efficiency:
 It must solve with the least amount of computational
resources such as time and
space.
 Producing an output as per the requirement within the
given resources (constraints).
Cont..
Example: Write the program that takes a number and displays
the square of the number.
1) int x;
cin>>x;
cout<<x*x*x;

2) int x,y;
cin>>x;
y=x*x*x;
cout<<y;
Cont..
Generality:
 Algorithm should be valid on all possible inputs.
Input/output:
 There must be a specified number of input values, and
one or more result values.
 Zero or more inputs and one or more outputs
Cont..
• The first step to solve the problem is obtaining ones own
abstract view, or model, of the problem.
• This process of modeling is called abstraction.
• The model defines an abstract view to the problem. The
model should only focus on problem related stuff.
Abstraction Cont..
• Is a process of classifying characteristics as relevant and
irrelevant for the particular purpose at hand and ignoring
the irrelevant ones.
Example: model students of GOU.
• Relevant:
Char Name[15];
Char ID[11];
Char Dept[20];
int Age, year;
• Non relevant
float age, weight;
Cont..
How do data structures model the world or some part of the
world?
•value held by a data structure represents some specific
characteristic of the world
•The characteristic being modeled restricts the possible
values held by a data structure the characteristic being
modeled restricts the possible operations to be performed on
the data structure . using the model, a programmer tries to
define the properties of the problem.
These properties include
 the data which are affected and
 the operations that are involved in the problem
an entity with the properties just described is called an
abstract data type (adt). 17
Abstract Data Types
Consists of data to be stored and operations supported on
them.
Is a specification that describes a data set and the operation
on that data.
The ADT specifies:
 What data is stored.
 What operations can be done on the data.
Does not specify how to store or how to implement the
operation.
Is independent of any programming language
Cont..

Example: ADT employees of an organization:


 This ADT stores employees with their relevant attributes and
discarding irrelevant.
attributes.
Relevant:- Name, ID, Sex, Age, Salary, Dept, Address
Non Relevant :- weight, color, height
Cont..
 adt ( abstract data type) is a mathematical model of a data
structure. it describes a container which holds a finite
number of objects .
 The operations which may be performed on the container
may be basic (e.g., insert, remove, etc.) or may be based
on the relationship (e.g, given an object (possibly already
in the container), find the next largest object).
 We will find that we cannot optimize all operations
simultaneously and therefore we will have to give
requirements for which operations must be optimal in
both time and memory.

20
A program
• a set of instruction which is written in order to solve a
problem.
 A solution to a problem actually consists of
two things:
A way to organize the data
Sequence of steps to solve the problem
• Therefore, a program =Data structures + Algorithm
Arrays
• Array
• Group of consecutive memory locations
• Same name and type
• To refer to an element, specify
• Array name
• Position number
• Format:
arrayname[ position number ]
• First element at position 0
• n element array named c:
• c[ 0 ], c[ 1 ]...c[ n – 1 ]

22
Fig. 6.1 | 12-element array.

23
Defining Arrays
When defining arrays, specify
Name
Type of array
Number of elements
arrayType arrayName[ numberOfElements ];
Examples:
int c[ 10 ];
float myArray[ 3284 ];
Defining multiple arrays of same type
Format similar to regular variables
Example:
int b[ 100 ], x[ 27 ]; 24
Array Examples
Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
If not enough initializers, rightmost elements become 0
int n[ 5 ] = { 0 }
All elements 0
If too many initializers, a syntax error occurs
If size omitted, initializers determine it
int n[ ] = { 1, 2, 3, 4, 5 };
5 initializers, therefore 5 element array

25
Function
A function is a group of statements that together perform a
task. Every C++ program has at least one function, which is
main(), and all the most trivial programs can define
additional functions.
You can divide up your code into separate functions.
How you divide up your code among different functions is
up to you, but logically the division usually is such that
each function performs a specific task.
The C++ standard library provides numerous built-in
functions that your program can call.

26
Defining a Function

• The general form of a C++ function definition is as follows


return_type function_name( parameter list )
{ body of the function}
A C++ function definition consists of a function header and a
function body. Here are all the parts of a function −
Return Type − A function may return a value. The return type
is the data type of the value the function returns. Some
functions perform the desired operations without returning a
value. In this case, the return type is the keyword void.
Function Name − This is the actual name of the function. The
function name and the parameter list together constitute the
function signature.
27
Cont..
Parameters − A parameter is like a placeholder. When a
function is invoked, you pass a value to the parameter.
This value is referred to as actual parameter or argument.
The parameter list refers to the type, order, and number of
the parameters of a function. Parameters are optional; that
is, a function may contain no parameters.
Function Body − The function body contains a collection
of statements that define what the function does.

28
Cont..
• Example Following is the source code for a function called
max(). This function takes two parameters num1 and num2
and return the biggest of both function returning the max
between two numbers
int max(int num1, int num2)
{
int result;
if (num1 > num2)
result = num1;
else result = num2;
return result;
}
29
Function declaration
A function declaration tells the compiler about a function's name,
return type, and parameters.
tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately.
A function declaration has the following parts
return_type function_name( parameter list );
For the above defined function max(),
following is the function declaration −
int max(int num1, int num2);
Function declaration is required when you define a function in one
source file and you call that function in another file. In such case, you
should declare the function at the top of the file calling the function.

30
Calling a Function
While creating a C++ function, you give a definition of
what the function has to do.
To use a function, you will have to call or invoke that
function.
When a program calls a function, program control is
transferred to the called function.
A called function performs defined task and when it’s
return statement is executed or when its function-ending
closing brace is reached, it returns program control back
to the main program.
To call a function, you simply need to pass the required
parameters along with function name, and if function
returns a value, then you can store returned value.
31
Declaring, defining and calling function Cont …
#include<iostream>
using namespace std;
int sum(int x,int y);//declaring function
int main()
{ int a=10;
int b=9;
int c=sum(a,b);//calling function
cout<<c;}
int sum(int x,int y)//defing function
{
return(x+y);
}
Uot put=19 32
Pointer
Pointers:     is a variable contain the address of another
variable.
If a variable contains address of another variable than it is said
that first variable points to second. All operation perform on
pointers are done through two operators '*' and '&'.
'&' is a unary operator that returns a memory address of a
variable.
'*' is complement of '&' and return value stored at a memory
location stored in a pointer. '*'
can interpreted as statement "at address" while '&' can be
interpreted as statement "address of".
Pointer Declaration:      Declaring a pointer variable is quite
similar to declaring a normal variable all you have to do is to
insert a star '*' operator before it.
33
Cont..
General form of pointer declaration is –
data type* name;
where data type represent the type of data  to which pointer
thinks it is pointing to.
Multiple pointers of similar type can be declared in one
statement but make sure you use * before every one
otherwise they will become a variable of that type.
Example:    int *p;   
float *f1,*f2;   
char *ch;

34
Cont.…
Pointer Assignment: Once we declare a pointer variable we
must point it to a value by assigning the address of the
variable 
Example:    int *p;   
int x; p=&x;    
The value of one pointer can be assigned to another pointer
using assignment operator '=' .
In this value of right hand side points to memory address of
variable stored in left hand side pointer. As a result both
pointers point to same memory location after this expression.
Pointer of similar type can be used in expression easily as
shown below but for different type pointers you need to type
cast them as shown in next section.
35
Cont…

pointer
powerful, but difficult to master
Simulate call-by-reference
Close relationship with arrays and strings

36

You might also like