You are on page 1of 48

Data Structures

Lecture 1,2,3

FURC Dr. Imran Daud


Course Contents
• Overview, Introductory concepts
• Data Types, meaning and implementation
• Abstract data types
• Arrays (revisited)
• Structures
• Stacks (recursion)
• Queues
• Linked Lists

FURC Dr. Imran Daud


Course Contents
• Indexing Methods
– Hashing
• Trees (traversal, implementation)
• Binary Trees
• Binary Search Trees
• Balanced Search Trees (AVL Tree)
• Heaps
• Splay Trees
• Graphs, adjacency matrices and lists

FURC Dr. Imran Daud


Books
• Text Books:
– C++ Data Structures by Nell Dale and David Teague
– Data structures using C and C++”, Yedidyah Langsam,
Moshe J Augenstein and Aaron M. Tenenbaum,
• Reference Books
– D. Wood: “Data structures, algorithms and
performance”, Addison-Wesley, 1993
– Any other book on Data Structures

FURC Dr. Imran Daud


Assignment Policy
• DO NOT copy assignments
– Both of the copy cases will be graded zero
• Submission time will be 1500 hrs on the due date
– NO credit on LATE submission of any deliverable.
• No excuse of USB/email servers not working
• Sorry! No Exceptions

FURC Dr. Imran Daud


Weightage
• Mid Term 25%
• Quizzes -
• Assignments -
• Project -
• Final Test 50%

• Quizzes : (Unannounced)
• Assignments : 1 Every 3 weeks

FURC
Why Data Structures?
• All types of tasks require some kind of data to be manipulated. By
creating new ways to manage (access and change) data, we can
make programs more efficient, and thus obtain more reliable and
faster results. Different types of programs require different ways of
handling data, however, standards exists between various
programs. This course gives you a peek into those standards, into
the world of data structures.

FURC
Data Structures: Definition
• Data structures are some objects that we generate to
store data in them , these data can be
– Usually more than one piece of data
– Should provide legal operations on the data
– The data might be joined together (e.g. in an array): a
collection

FURC
Data Structures: Definitions
• A collection of data elements whose organization is
characterized by accessing operations that are used
to store and retrieve the individual data elements;
• The logical arrangement of data as used by a system
for data management; a representation of a data
model in computer form

FURC
Abstract Data Type ADT
• A data type whose properties (domain and
operations) are specified independently of any
particular implementation.

• ADT is a mathematical model which gives a set of


utilities available to the user but never states the
details of its implementation.

FURC
Abstract Data Types (ADTs)

ADT package exposes capabilities,


hides implementation details

Different implementations possible


for same ADT

Much of our concern in course is how to implement


data structures as ADTs.

FURC
Introduction to Data Structures

FURC
Data Structures
• A data structure is a user-defined abstract data type
• Examples:
– Complex numbers: with operations +, -, /, *, magnitude,
angle, etc.
– Stack: with operations push, pop, peek, isempty
– Queue: enqueue, dequeue, isempty …
– Binary Search Tree: insert, delete, search.
– Heap: insert, min, delete-min.

FURC
Data Structure Design
• Specification
– A set of data
– Specifications for a number of operations to be performed
on the data
• Design
– A lay-out organization of the data
– Algorithms for the operations
• Goals of Design: fast operations

FURC
Implementation of a Data
Structure
• Representation of the data using built-in data types
of the programming language (such as int, double,
char, strings, arrays, structs, classes, pointers, etc.)

• Language implementation (code) of the algorithms


for the operations

FURC
OOP and Data Structures
• When implementing a data structure in non-OOP languages
such as C, the data representation and the operations are
separate

• In OOP languages such as C++, both the data representation


and the operations are aggregated together into what is called
objects

• The data type of such objects are called classes.


• Classes are blue prints, objects are instances.

FURC
Data Structures: More specifically
– A data structure is a way of grouping fundamental types
(like integers, floating point numbers, and arrays) into a
bundle that represents some identifiable thing.
• For example, a matrix may be thought of as the bundle of the
number of rows and columns, and the array of values of the
elements of the matrix. This information must be known in order
to manipulate the matrix.

– C introduced the struct for declaring and manipulating data


structures. C++ extended the struct to a class

FURC
Data Structures: More specifically
• Data structure: An arrangement of data in a
computer’s memory
– Arrays, linked lists, stacks, trees, hash tables.

• Algorithms manipulate the data in these structures


in order to accomplish some task.
– Inserting an item, search for an item, sorting.

FURC
ADT and Data Structures
• ADT is implementation independent. For example, it only
describes what a data type List consists (data) of and what are
the operations it can perform, but it has no information about
how the List is actually implemented.
• Whereas data structure is implementation dependent, as in the
same example, it is about how the List is implemented i.e.,
using array or pointer. Ultimately, data structure is how we
implement the data in an abstract data type.

FURC
Why different data structures
• Each data structure has different advantages and
disadvantages, and will be useful for different types
of applications.
– Example: arrays
– Fast access: if we know the index of the item we are
looking for
– Deletion is slow, size is fixed.

FURC
A Real Life Example • Lisa
Electronic Phone Book • Michele
• John
Contains different DATA: • 110
- names • 622-9823
- phone number • 112-4433
• 75
- addresses • Bronson
Need to perform certain OPERATIONS: • Paola
- add
- delete
- look for a phone number
- look for an address

How to organize the data so to optimize the


efficiency of the operations
FURC
Word about Arrays!
• Lets Get Started:

• Arrays are data structures


– Finite
– Contiguous
– Fast
– Direct Access
– All elements of same data type
– Insertion / Deletion ??? HOW?? 

FURC
The first Data Structure
• An Array!
The simplest form of an Array is a one dimensional array
that may be defined as a finite ordered set of homogenous
elements

• For Example
int a[100];

FURC
Basic Operations
• Extraction
– A function that accepts an array “a” and an index “i”, and
returns an element of the array.
– Example
a[i]
• Storing
– It accepts array “a” an index “i” and an element x.
– Example
– a[i]=x

FURC
One Dimensional Array
• range = upper - lower+1 Lower
Bound [0]

• Neither the upper bound nor the


lower bound and the range can
be changed during the program
Range
execution.

Upper
Bound

FURC
Initializing an Array
What is the output of the following array?
• int values[5]={1,2,3};

• double junk[5]={0};
• double junk[5]={ };

• int values[ ]={2,3,4};


• sizeof values
• sizeof values[0]

FURC
Implementation of 1Dimenional
Array
• int b[100];
– Reserves 100 successive locations, each large enough to contain a single
integer.
• The address of the first of these locations is called the Base
Address: base(b)
• Reference to element b[0] is to the element at location base(b)
• Reference to b[1] is to the element at
base(b) + 1
Hence
b gives you the starting memory address of the array b

FURC
Memory view of an array
int a[5] 2 3 4 7 8

//Help me give output of this


program
a[0] 2 0x4
void main(void) a[1] 3 0x8
{
a[2] 4 0xC
int a[5] = { 2,3,4,7,8 };
cout << a[3] << endl; a[3] 7 0x10
cout << a <<endl; a[4] 8 0x14
cout << *(a+1) <<endl;
cout << *a+1 <<endl;
}
FURC
*a +1 without brackets leads to adding 1 to
contents (value) of a[0]

FURC
Array of Characters
a e I o u
• Char vowels[5]={‘a’, ’e’ ,’I’, ’o’, ’u’,}
• Char vowels[ ]={‘a’, ’e’ ,’I’, ’o’, ’u’,}

• Char name[10]=“niit bit”


N I I T B I T \0 \0

• Char name[ ]=“niit bit”

• How can you display a string stored in an


N I I T B I T
array?
• cout<<name<<endl;

FURC Dr. Imran Daud


How to determine length of the
string
#include <iostream.h>
#include <conio.h>
#include <stdio.h>
int len_str(char s[25]);
int len_str_while(char s[25]);

void main(void)
{
char len[25];
cin >> len;
cout << len_str(len) << endl << len_str_while(len);
}
//function with for loop
int len_str(char s[25])
{
for (int i = 0; s[i] != '\0'; i++);
return i;
}

FURC Dr. Imran Daud


Cont…
//another method using while loop
int len_str_while(char s[25])
{
int i=0;
while (s[i] != '\0')
{
i++;
}
return i;
}

FURC Dr. Imran Daud


Structures

FURC Dr. Imran Daud


Structure
• This is the second Data structure that we will study
and one of the powerful features of C language
• Consider Student Data
• How to store names, age, address, city, CGPA for
students
• Can u suggest how to create a database for it?

FURC Dr. Imran Daud


What is a Structure?
• A structure is an aggregate data structure used to keep
different pieces of information together as a single data
record.

• A structure is like an array except that each element can have


a different data type, and the elements in a structure have
names instead of subscript values

FURC Dr. Imran Daud


Declaring a struct Variable
• Syntax of the struct data type:

• struct name
{
type field_name1;
type field_name2; ...
};
where
– name is the name of the record type established by the struct,
– each type field_name defines a field in the record,
– the field definitions are separated by semicolons, and
– the struct has a trailing semicolon.

FURC Dr. Imran Daud


Example of declaring a struct:
• /* declare a struct type (template) with name "Person_Record"*/
struct Person_Record
{
char name[20];
int age;
};
/* Now, allocate memory */
Person_Record My_Record;
struct Person_Record My_Record; /* a single record */
struct Person_Record My_Array[100]; /* an array of records */

FURC Dr. Imran Daud


More about structures
• Normally structure is defined as global variable
• Its instances are created in main program or any other function
• The memory is not allocated when structure is defined. But
when the instance of a structure is created then memory is
reserved.
• Hence structure is like a cookie mold!  with no cookies
unless you put the mixture of ingredients… 
• Hence structure stand alone is a template… and it cannot be
initialized. You need to Instantiate it or declare a variable of
type structure

FURC Dr. Imran Daud


Initializing a Structure Variable

• To initialize a structure, follow the structure variable


name with an equal sign, followed by a list of
initializes enclosed in braces.
• Example:
• Struct Person_Record
• {
char name[5];
int semster;
• };
struct Person_Record My_record = { “niit", 8 };

FURC Dr. Imran Daud


Using a Structure Variable

• There are two ways to reference (access) the fields in


a structure:

• The structure itself.


• A pointer to the structure.

FURC Dr. Imran Daud


I/O of Structures

• When you use cin/cout you must read/write a


structure field-by-field.

• emp.age = 20
• Cin >> emp.age
• Cout << emp.age

FURC Dr. Imran Daud


Structures as Function
Parameters

• The entire structure is copied to the function, i.e., a


structure is passed by value.
• A pointer to a structure can be passed to achieve
call-by-reference.
• Individual field of a structure can be passed as a real
parameter to a function.
• It is possible for a function to return a structure or a
pointer to a structure.

FURC Dr. Imran Daud


Examples:
• Passing an entire structure
void func(Person_Record); //prototype of function
...
Person_Record My_Record;
func(My_Record); /* call-by-value */

• Passing a pointer to a structure


void func(Person_Record *);
...
Person_Record My_record;
func(&My_record); /* call-by-reference , pointer*/

• Passing the address of a struct is faster, changes are reflected in


My_Record

FURC Dr. Imran Daud


Nested Structures
• When one of the fields of a structure is itself a structure, it is
called a nested structure.
• Struct DateofBirth {
int years;
int months;
int day; };
Struct Emp {
char[25] name;
DateofBirth Dob;
};

FURC Dr. Imran Daud


Self-Referential Structures
• We can declare pointers to structures that have not
yet been declared. These are called dynamic data
structures.
• This permits us to create self-referential structures,
as well as mutual-referential structures.
• Example:
struct listnode
{ int nodedata;
struct listnode *nextnode; };

FURC Dr. Imran Daud


Example Program
• Will do detailed program next time in the class!

• Here is a simple program

FURC Dr. Imran Daud


#include <iostream.h>
#include <conio.h> do {
#include <stdio.h>
cout << "Please enter Name of the
struct Date{ employee"
int mm; cin >> d[i].name ;
int dd;
int yy; cout << "Please enter age" << endl;
};
cin >> d[i].age ;
cout << "Please enter date (dd,mm,yyyy)"
struct data{ cin >> d[i].hireDate.dd;
char name[25]; cin >> d[i].hireDate.mm;
int age; cin >> d[i].hireDate.yy;
struct Date hireDate; cout << "Would like to enter more data?
}; (y/n)“;

void main(void){ i++;


cin >> ch;
data d[20];
//creates array of type data limit 20 }while (ch != 'n');
int i = 0;
char ch; for (int j=0; j < i; j++)
{
cout << endl << d[j].name;
}
}

FURC Dr. Imran Daud


Array

2 3 7 8

How to add 4

2 3 4 7 8

How to add 1 in the array?

FURC Dr. Imran Daud

You might also like