Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
43 views

Chapter 1.1 Introduction Data Structure

Introduction to C++ programming Revision on Object Oriented Programming Concepts Introduction to Data Structures Abstract data Types Abstraction Algorithms Properties of an algorithm Algorithm analysis concepts Complexity analysis Asymptotic Analysis

Uploaded by

Bedasa Wayessa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Chapter 1.1 Introduction Data Structure

Introduction to C++ programming Revision on Object Oriented Programming Concepts Introduction to Data Structures Abstract data Types Abstraction Algorithms Properties of an algorithm Algorithm analysis concepts Complexity analysis Asymptotic Analysis

Uploaded by

Bedasa Wayessa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

Course Title: Data Structure & Algorithm.

Credit Hour: 3 hrs.


Course Code: CoSc2091.
ECTS: 5 [2 Lecture hours and 3 Lab hours]
Lecture Schedule: Every ____________

Bedasa Wayessa
bedonaf@gmail.com

Data Structures and Algorithms - CoSc2091 1


Classroom Rules
• Late comer will only tolerated for the first 5 minutes of every class
• Talk to me and Not to each other
• Do not sleep
• Do not use phones
• Fail to obey the Classroom rule  face 2  3 class ban

Data Structures and Algorithms - CoSc2091 2


Assignment Submission
 Guidelines for submission will be provided with every assignment
 Re-grade requests will ONLY be entertained within one week after
the assignments have been handed back to students or assignment due
date
 IMPORTANT: Late submissions are allowed ONLY until 1 day following
the deadline, with 10% marks deduction.
 IMPORTANT: Late + Copy = ZERO Marking

Data Structures and Algorithms - CoSc2091 3


QUIZZES
• Quizzes will NOT be announced
• Re-grade requests will only be entertained within one week after the
marked quizzes have been handed back to students [with tangible and
acceptable reason only]

Data Structures and Algorithms - CoSc2091 4


Course Description
 This course focuses on the study of data structures, algorithms and
program efficiency.
 Topics include:
– analysis of time and space requirements of algorithms;
– program efficiency improving techniques, abstract data types such as
linked lists, stacks, queues, trees (traversal, implementations);
– simple searching algorithms (linear search, binary search, ... ), simple
sorting algorithms (bubble sort, insertion sort, selection sort, ... ),
advanced sorting algorithms (merge sort, quick sort, heap sort ...)

Data Structures and Algorithms - CoSc2091 5


Course Objectives
 To introduce the most common data structures like
– stack,
– queue,
– linked list.
 To give alternate methods of data organization and representation.
 To enable students use the concepts related to Data Structures and
Algorithms to solve real world problems.
 To practice Recursion, Sorting, and searching on the different data
structures.
 To implement the data structures with a chosen programming language.

Data Structures and Algorithms - CoSc2091 6


Chapters
• Chapter 1. Introduction to Data Structures and Algorithms
(4hr)
– 1.1. Introduction to Data Structures
• 1.1.1 Abstract data Types
• 1.1.2 Abstraction
– 1.2. Algorithms
• 1.2.1. Properties of an algorithm
• 1.2.2. Algorithm analysis concepts
• 1.2.3. Complexity analysis
– 1.3. Asymptotic Analysis

Data Structures and Algorithms - CoSc2091 7


Chapters
• Chapter 2: Simple Sorting and Searching Algorithms (4hr)
– 2.1. Sorting Algorithms
• 2.1.1. Insertion sort
• 2.1.2. Selection Sort
• 2.1.3. Bubble sort
• 2.1.4. Pointer sort
– 2.2. Searching Algorithms
• 2.2.1. Linear Search (Sequential search)
• 2.2.2. Binary Search

Data Structures and Algorithms - CoSc2091 8


Chapters
• Chapter 3: Linked Lists (4hr)
– 3.1. Review on Pointer and Dynamic Memory allocation
– 3.2. Singly Linked List and Its Implementation
– 3.3. Doubly Linked List and Its Implementation
– 3.4. Circular Linked Lists and Its.
• Chapter 4: Implementation Stacks (4hr)
– 4.1. Properties of Stack
– 4.2. Array Implementation of Stack
– 4.3. Linked List Implementation of Stack
– 4.4. Application of Stack
• 4.4.1. Evaluation of Algebraic Expression
• 4.4.2. Infix and Post fix (RPN) conversion
• 4.4.3. Function calls

Data Structures and Algorithms - CoSc2091 9


Chapters
• Chapter 5: Queue (4hr)
– 5.1. Properties of Queue
– 5.2. Array Implementation of Queue
– 5.3. Linked List Implementation of Queue
– 5.4. Double Ended Queue (Deque)
– 5.5. Priority Queue
– 5.6. Application of Queues
• Chapter 6:Trees (4hr)
– 6.1. Binary Tree and Binary Search Trees
– 6.2. Basic Tree Operations
– 6.3. Traversing in a Binary tree
– 6.4. General Trees and Their Implementations

Data Structures and Algorithms - CoSc2091 10


Chapters
• Chapter 7: Graphs (4hr)
– 7.1. Introduction
– 7.2. Directed vs Undirected graph
– 7.3. Traversing Graph
• Chapter 8: Advanced Sorting and Searching algorithms (4hr)
– 8.1. Advanced Sorting
• 8.1.1. Shell sort
• 8.1.2. Quick sort
• 8.1.3. Heap Sort
• 8.1.4. Merge sort
– 8.2. Advanced Searching
• 8.2.1. Hashing
Data Structures and Algorithms - CoSc2091 11
Teaching - Learning methods
• Two contact hours of lectures, three hours of lab and two hours of tutorials
per week.
• Students do home assignments.
Assessment method
Task Task Type Session Max Mark
1 Quizzes Lab & Theory Individual 20
2 Assignments Lab & Theory Individual 10
3 Project Lab Individual/group 20
4 Final Exam both Individual 50
Total 100

Data Structures and Algorithms - CoSc2091 12


Course Information
• Refrences/Textbooks
• Robert Lafore, “Data Structures and Algorithms in JAVA, 2nd Ed.”,
Sams Publishing
• Jean Paul Tremblay, Paul G. Soreson, “An Introduction to Data
Structures with Applications”, Mc.Graw Hill Computer Science Series
• E. Horowitz, S.Sahni and Dinesh Mehta. Fundamentals of data
structures in C++, W.H Freeman and Company (1995)
• Sanjay Pahuja, A practical approach to data structures and algorithms,
new age International publishers, 2008
• https://cplusplus.com/doc/tutorial/
• https://www.onlinegdb.com/online_c++_compiler

Data Structures and Algorithms - CoSc2091 13


Mapping Learning Outcomes to Skill Sets
• General Objective
• Combine fundamental data structures and algorithmic techniques to
create a complete algorithmic solution to a given problem.
• Learning outcomes
• Understand the most common concepts of data structures like stack,
queue and linked list.
• Implement the Sorting and searching concepts.
• Use the concepts related to Data Structures and Algorithms to solve
real world

Data Structures and Algorithms - CoSc2091 14


Introduction to Data Structure and
Algorithms

Part I: Data Structure

Data Structures and Algorithms - CoSc2091 15


Outline
 Introduction to C++ programming
– Revision on Object Oriented Programming Concepts
 Introduction to Data Structures
– Abstract data Types
– Abstraction
 Algorithms
– Properties of an algorithm
– Algorithm analysis concepts
– Complexity analysis
 Asymptotic Analysis

Data Structures and Algorithms - CoSc2091 16


Learning DS and Algorithms in C++
 Establishes solid foundation for easy passage in subsequent chapters.
 Creating, building, and running a simple C++ program
 Constructing an abstract data type to make a user-defined data type.
 Analyzing the complexity of algorithms to measure the performance
of the code.
 Technical requirements
 A desktop PC or Notebook with Windows, Linux, or macOS
 GNU GCC v5.4.0 or above
 Code::Block IDE v17.12 (for Windows and Linux OS) or Code::Block
IDE v13.12 (for macOS) or
 Dev-Cpp 5.11 TDM-GCC 4.9.2 Setup(for windows with d/t ver)

Data Structures and Algorithms - CoSc2091 17


Introduction to basic C++
 Before we go through the Data Structures and Algorithms in C++:
– We need to have a strong, fundamental understanding of the language
itself.
– In this section, we are going to build a simple program, build it, and
then run it.
– We are also going to discuss the fundamental and advanced data types,
and before we move on to algorithm analysis, we are going to discuss
control flow in this section.
 Basics of C++  Program structure  Compound data types
 Structure of a program  Control Structures  Arrays
 Variables and types  Functions  Pointers
 Constants
 Overloads and templates  Classes (I)
 Operators
 Name visibility  Exceptions
 Basic Input/Output
Data Structures and Algorithms - CoSc2091 18
Creating your first code in C++
 In C++, the code is executed from the main() function first.
 The function itself is a collection of statements to perform a specific task.
 As a result of this, a program in C++ has to contain at least one function
named main().
 The following code is the simplest program in C++ that will be
successfully compiled and run:
//When we run it
HelloCpp.cpp E:\C++ Project\Program
#include <iostream> λ g++ HelloCpp.cpp -o Hello
using namespace std;
E:\C++ Project\Program
int main() { λ Hello
cout<<"Hello C++\n"; Hello C++!
return 0;
}
E:\C++ Project\Program

Data Structures and Algorithms - CoSc2091 19


Fundamental Data Types
 In C++, we have to define a variable to be of a specific data type so it
can only store the specific type of variable that was defined previously.
 Here is a list of the fundamental data types in C++.
 Boolean data type (bool), which is used to store two pieces of
conditional data only—true or false
 Character data type (char, wchar_t, char16_t, and
char32_t), which is used to store a single ASCII character
 Floating point data type (float, double, and long double),
which is used to store a number with a decimal.
 Integer data type (short, int, long, and long long),
which is used to store a whole number.

Data Structures and Algorithms - CoSc2091 20


Fundamental Data Types
 Here is a list of the fundamental data types in C++ cont.’..
 No data (void), which is basically a keyword to use as a placeholder
where you would normally put a data type to represent no data
 The syntax to declare variables in C++ is:
 int age;
 Here, age - a variable and int - data type of age
 // assign 19 to age
 age = 19;
 // print the variable
 cout << age;

Data Structures and Algorithms - CoSc2091 21


More complex Data Types (Pointers, Arrays, & Structures)
 More Complex fundamental in C++.
 A pointer is a variable that holds the value of Var an address.
 Two essential operators are used to manipulate pointers(* and &).
 An array is a collection of elements of the same type.
 Given any type T and a constant N, a variable of type T[N] holds an
array of N elements, each of type T.
 Each element of the array is referenced by its index, that is, a number
from 0 to N −1.
 A structure is useful for storing an aggregation of elements.
 Unlike an array, the elements of a structure may be of different types.
 Each member, or field, of a structure is referred to by a given name.

Data Structures and Algorithms - CoSc2091 22


Defining the Variables using Fundamental Data Types

 There are two ways to create a variable


– by defining it or by initializing it.
 Defining a variable will create a variable without deciding upon its initial
value.
 Initializing variable will create a variable and store an initial value in it.

Here is the code snippet for And here is the sample code snippet
how we can define variables: of how initializing variables works:
int iVar; int iVar = 100;
char32_t cVar; char32_t cVar = 'a';
long long llVar; long long llVar = 9223372036854775805;
bool boVar; bool boVar = true;

Data Structures and Algorithms - CoSc2091 23


Controlling the Flow of the code
 As we discussed earlier,
– Statements are fragments of the C++ program that are executed in
sequence.
– The body of any function is a sequence of statements.
– the C++ program is run from the main() function by executing each
statement one by one from the beginning to the end.

 However, we can change this path using flow control statements.


 There are several flow control statements in C++.
 Conditional int main() {
int n = 1; // declaration statement
 Loop
n = n + 1; // expression statement
cout << "n = " << n << '\n'; // expression statement
return 0; // return statement
}

Data Structures and Algorithms - CoSc2091 24


Controlling the flow of the code
 Conditional statement
– It is one of the elements that can modify how a program flows.
– Only the line in the true condition will be run when using this.
– We can use the if and else keywords to apply this statement.
// If_Else.cpp
#include <iostream>
using namespace std;
int main () {
int i;
cout << "Please enter an integer value: ";
cin >> i;
cout << "The value you entered is ";
if(i > 100)
cout << "greater than 100.";
else
cout << "equals or less than 100."<< endl;
return 0;
}
Data Structures and Algorithms - CoSc2091 25
Controlling the flow of the code
 Loop statement
– In C++ they are for, while, and do...while.
– The for loop is usually used when we know how many iterations
we want, whereas while and do...while will iterate until the desired
condition is met.
// for_loop.cbp // while_loop.cbp
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int main () { int main () {

for(int i = 0; i<10; i++){ while(i<10){


cout<< “i = “<<i; cout<< “i = “<<i;
} i++;
cout<<endl; }
cout<<endl;
return 0; return 0;
} }

Data Structures and Algorithms - CoSc2091 26


Controlling the flow of the code
 Loop statement Summary
Snp Loop Type and Description
1 while loop
– First checks the condition, then executes the body
initialization expression;
while (test_expression) { update_expression; }

2 for loop
– firstly initializes, then, condition check, execute body, update.
for (initialization expr; test expr; update expr){}

3 do-while loop
– firstly, execute the body then condition check
initialization expression;
do { update_expression; } while (test_expression);
Data Structures and Algorithms - CoSc2091 27
Developing Abstract Data Types
 An abstract data type (ADT) is a type that consists of a collection of data
and associated operations for manipulating the data.
 The ADT will only mention the list of operations that can be performed but
not the implementation.
 The implementation itself is hidden, which is why it's called abstract.
 E.g.:- Imagine we have a DVD player we usually use in our pleasure time.
 Regarding the process flow:
 Abstraction is hiding the implementation details of the operations that
are available in the ADT
 Information hiding is hiding the data which is being affected by that
Implementation
 Encapsulation is grouping all similar data and functions into a group

Data Structures and Algorithms - CoSc2091 28


OOP Concepts - Revision
 OOP Summary
– The procedural paradigm focuses on designing functions.
– OOP enables you to develop large-scale software effectively.
– The OO Paradigm couples data and functions together into objects.
– Software design using the object-oriented paradigm focuses on objects
and operations on objects.
Object A Object B

data data
communications
functions functions
Object C

functions

data

Data Structures and Algorithms - CoSc2091 29


OOP Concepts - Revision
 Benefits of OOP:
– Object-Oriented Design Goals:
– Software implementations should achieve robustness,
adaptability, and reusability.
– we want software to be robust, that is, capable of handling
unexpected inputs that are not explicitly defined for its application.
– Software needs to be able to evolve over time in response to
changing conditions in its environment - adaptability (also called
evolvability).

Data Structures and Algorithms - CoSc2091 30


OOP Concepts - Revision
 Object-Oriented Design Principles
– Objects
– Classes
– Inheritance
– Data Abstraction
– Data Encapsulation
– Polymorphism

Data Structures and Algorithms - CoSc2091 31


OOP Concepts - Revision
 Classes and Objects
– Class: a type definition that includes both
– data properties, and
– operations permitted on that data
– Object: a variable that
– is declared to be of some Class
– therefore includes both data and operations for that class
– Appropriate usage:
– “A variable is an instance of a type.”
– “An object is an instance of a class.”

Data Structures and Algorithms - CoSc2091 32


OOP Concepts - Revision
 Basic Class Syntax

• A class in C++ consists of its members.

– A member can be either data or functions.

• The functions are called member functions (or methods)

• Each instance of a class is an object.

– Each object contains the data components specified in class.

– Methods/functions are used to act on an object.

– Class Members:

– Public member is visible to all routines and may be accessed by any


method in any class.

– Private member is not visible to non-class.

• Restricting access is known as information hiding.

Data Structures and Algorithms - CoSc2091 33


OOP Concepts - Revision
 Simple class and object creation example in C++
#include <iostream>
using namespace std;

class Animal{ //class Name


private:
string name;
public:
void bark(){
cout<<" woo-oow"<<endl;
}
};
int main(int argc, char** argv) {
Animal cat; // object name
cout<<"Here: ";
cat.bark();
return 0;
}
Data Structures and Algorithms - CoSc2091 34
OOP Concepts - Revision
 Inheritance
– Inheritance is a way to reuse once written code again and again.
– The class which is inherited is called base class & the class which inherits is called
derived class.
– So when, a derived class inherits a base class, the derived class can use all the
functions which are defined in base class, hence making code reusable.
Syntax class derived-class-name : visibility-mode base-class-name {
//members of derived class
}

class dog : public Animal{


private:
string name;
public:
void bark(){
cout<<" woo-oow"<<endl;
}
};
Data Structures and Algorithms - CoSc2091 35
OOP Concepts - Revision
 Data Abstraction
– An abstract class cannot be used to create objects.
– An abstract class can contain abstract functions, which are
implemented in concrete derived classes.
– Data abstraction is a programming (and design) technique that
relies on the separation of interface and implementation.
– Sometimes a base class is so abstract that it cannot have any
specific instances. Such a class is referred to as an abstract class.
– In C++, we use classes to define our own abstract data types
(ADT).
– sort: you can sort an array with this C++ call, BUT you do not know
the algorithm.

Data Structures and Algorithms - CoSc2091 36


OOP Concepts - Revision
 Data Abstraction

#include <iostream>
using namespace std; int main () {

class Shape { cout << "Hello World\n";


public: Square s;
int width; s.width = 10;
//method declaration no body cout << s.area ();
int area () const; //abstract
}; return 0;
//inheritance }
class Square:public Shape {

public:
//method definitions Output:
int area () { Hello World
return width * width; 100
}
};
Data Structures and Algorithms - CoSc2091 37
Abstract Data Type(ADT)
 An ADT is a class that has a defined set of operations and values.
 In programming, an ADT has the following features:
 An ADT doesn't state how data is organized, and
 It provides only what's needed to execute its operations
• An ADT is a prime example of how you can make full use of data
abstraction and data hiding.
• This means that an abstract data type is a huge component of object-
oriented programming methodologies:
– enforcing abstraction, allowing data hiding (protecting information
from other parts of the program), and
– encapsulation (combining elements into a single unit, such as a
class).

Data Structures and Algorithms - CoSc2091 38


OOP Concepts - Revision
 Data Encapsulation
– It can also be said data binding.
– Encapsulation is all about binding the data variables and functions
together in class.
– Data Encapsulation combines data and functions into a single unit
called Class.
– When using Data Encapsulation, data is not accessed directly; it is
only accessible through the functions present inside the class.
– Data Encapsulation enables the important concept of data hiding
possible.

Data Structures and Algorithms - CoSc2091 39


OOP Concepts - Revision
 Data Encapsulation
 It also safeguards the data from other classes by limiting access.
 Basically it hides the data.
 Encapsulation also lead to data abstraction or hiding.
 As using encapsulation also hides the data.
 Restrict access to data so that it can be manipulated only in
authorized ways.
 Separate class declarations from implementation (e.g. public, private
in C++).

Data Structures and Algorithms - CoSc2091 40


OOP Concepts - Revision
 Data Encapsulation: C++ Data Hiding Using the private Specifier
class Rectangle {
private:
// private Variables required for area
int length;
public:
// Public Setter function for length
void setLength(int len) {
length = len;
}

// Getter function for length


int getLength() {
return length;
}
// Function to calculate area
int getArea() {
return length * length;
}
};
Data Structures and Algorithms - CoSc2091 41
OOP Concepts - Revision
 Polymorphism
– It is a feature, which lets us create functions with same name but
different arguments, which will perform differently.
– That is function with same name, functioning in different way.
– Or, it also allows us to redefine a function to provide its new definition.

class Addition {
public:
int add(int X, int Y){ // Function with parameter
return X+Y; // this function addition of two Integer value
}
int add() { // Function with same name but without parameter
string a= "HELLO";
string b=“C++"; // in this function concatenation is performed
string c= a+b;
cout<<c<<endl;
}
};

Data Structures and Algorithms - CoSc2091 42


OOP Concepts - Revision
 Polymorphism
– The word polymorphism means having many forms.
– Polymorphism means that the same thing can exist in two forms.
– Polymorphism is in short the ability to call different functions by just
using one type of function call.

Shape
draw()

Triangle Rectangle Circle


draw() draw() draw()

Data Structures and Algorithms - CoSc2091 43


Outline
 Introduction to C++ programming
– Revision on Object Oriented Programming Concepts
 Introduction to Data Structures
– Abstract Data Types(ADT)
– Abstraction
 Algorithms
– Properties of an algorithm
– Algorithm analysis concepts
– Complexity analysis
 Asymptotic Analysis

Data Structures and Algorithms - CoSc2091 44


Introduction to Basic Data Structures
 Unit Objectives
 Upon completion of this Topic you should be able to:
 Identify data structures used to organize data in a computer
 Describe abstract data types used in the organization of data in the
computer
 Explain the data structures used to organize data for the efficient use
of the computer

Data Structures and Algorithms - CoSc2091 45


Introduction to Basic Data Structures
 Before introducing data structures we should understand that computers
do store, retrieve, and process a large amount of data.
 If the data is stored in well organized way on storage media and in
computer's memory then it can be accessed quickly for processing that
further reduces the latency and the user is provided fast response.
 Data structure refers to:
– A scheme for organizing data, or
– is an arrangement of data in computer's memory in such a way that it
could make the data quickly available to the processor for required
calculations.

Data Structures and Algorithms - CoSc2091 46


Introduction to Basic Data Structures
 Data structures also called data types are the particular ways of
organizing data in a computer so that it can be used efficiently.
 A Data structures is a group of data elements grouped together
under one name.
 These data elements, known as members, can have different types and
different lengths.
 Abstract data types (ADT) are set of values (the carrier set), and
operations on these values.
 The different data structures offer advantages to algorithm designers
in that they are able to know which one would enable efficient use of the
computer.

Data Structures and Algorithms - CoSc2091 47


Introduction to Basic Data Structures
 Key Terms:
 Data structure: the programmatic way of storing data so that data
can be used efficiently.
 Abstract data type: the carrier set together with their operations.
 Variable: C++ is a strongly-typed language, and requires every
variable to be declared with its type before its first use.
 The C++ language is a "case sensitive" language.
 Array, Lists, Linked Lists, Stack, Queues, Hashing and Trees.

Data Structures and Algorithms - CoSc2091 48


Introduction to Basic Data Structures
 A data structure should be seen as a logical concept that must address
two fundamental concerns.
– First, how the data will be stored, and
– Second, what operations will be performed on it?
 Data Structure = Organized Data + Allowed Operations
 As data structure is a scheme for data organization so the functional
definition of a data structure should be independent of its
implementation.
 The functional definition of a data structure is known as ADT (Abstract
Data Type) which is independent of implementation.
 The implementation part is left on developers who decide which
technology better suits to their project needs.
Data Structures and Algorithms - CoSc2091 49
Abstract Data Type
 An abstract data type (ADT) is a type that consists of a collection of
data and associated operations for manipulating the data.
 The ADT will only mention the list of operations that can be performed
but not the implementation.
 The implementation itself is hidden, which is why it's called abstract.
 Regarding the process flow, we need to take into account the ADT’s
implement abstraction, information hiding, and
encapsulation techniques.

Data Structures and Algorithms - CoSc2091 50


Introduction to Basic Data Structures
 Abstract Data Type: Example
 Stack ADT is a data structure which supports operations such as
– push :- Add an element to the top of a stack
– pop :- Remove an element from the top of a stack
– IsEmpty :-Check if the stack is empty
– IsFull :- Check if the stack is full
– Peek :- Get the value of the top element without removing it
 A stack can be implemented in a number of ways, for example using an
– array or using a linked list.
 Along with data structures introduction, in real life, problem solving is
done with help of data structures and algorithms.

Data Structures and Algorithms - CoSc2091 51


Assessment
 What is the definition of a data type?
 Describe briefly two ADTs that we studied in this section? In each case
specifying the necessary operations for each.
 Differentiate between Abstract Data Type, Data Type and Data Structure.

Data Structures and Algorithms - CoSc2091 52


Classification of Data Structures
 Designing and using data structures is an important programming skill.
 Data structure can be broadly classified into two categories as Linear
and Non-Linear.

Data Structures and Algorithms - CoSc2091 53


Classification of Data Structures
1. Linear and Non-linear data structures:
 In linear data structures the data elements are arranged in a linear
sequence like in an array, data processed one by one sequentially.
 Linear data structures contain following types of data structures:
– Arrays,
– Linked lists,
– Stacks and Queues
 In non-linear data structures, the data elements are not in sequence
that means insertion and deletion are not possible in a linear manner.
 Non-linear data structures contain following types of data structures:
– Tree and
– Graph

Data Structures and Algorithms - CoSc2091 54


Classification of Data Structures
2. Homogenous and Non-homogenous data structures:
– In homogenous data structures the data elements are of same type like
an array.
– In non-homogenous data structures, the data elements may not be of
same type like structure in ‘C’.
3. Static and Dynamic data structures:
– Static structures are ones whose sizes and structures associated
memory location are fixed at compile time,
– e.g., array.
– Dynamic structures are ones that expand or shrink as required during
the program execution and their associated memory location change,
– e.g., linked list.

Data Structures and Algorithms - CoSc2091 55


Operations Performed in Data Structure
 In data structure we can perform the operations like
 Traversing
 Insertion
 Deletion
 Merging
 Sorting
 Searching

Data Structures and Algorithms - CoSc2091 56


Some important DS: Arrays
 Arrays are unarguably easier data structures to use and access.
 An array is said to be a fixed length, ordered collection of values of the
same type stored in contiguous memory locations.
 But inserting an item to an array and deleting it from the array are
situation dependent.
 If you want to insert an item at a particular position which is already
occupied by some element then you have to shift all items one
position right from the position new element has to be inserted then
insert the new item.

Values: 2 1 5 3 4
Index: 0 1 2 3 4

Data Structures and Algorithms - CoSc2091 57


Some important DS: Arrays
 The time taken by insert operation is depend on how big the array is,
and at which position the item is being inserted.
 The same is true about deletion of an item.

#include <iostream>
using namespace std;

int main() {
int numbers[5] = {7, 5, 6, 12, 35};
cout << "The numbers are:\n"; The numbers are:
7
// Printing array elements 5
for (int i = 0; i < 5; ++i) { 6
cout << numbers[i] << "\n"; 12
} 35

return 0;
}

Data Structures and Algorithms - CoSc2091 58


Some important DS: Linked List
 Linked list DS provides better memory management than arrays.
 Because linked list is allocated memory at run time, so, there is no waste
of memory.
 Performance wise linked list is slower than array because there is no
direct access to linked list elements.
 Linked list is proved to be a useful data structure when the number of
elements to be stored is not known ahead of time.

//Creating a node
class Node {
public:
int value;
Node* next;
}; Data Structures and Algorithms - CoSc2091 59
Some important DS: Stack
 Stack is a last-in-first-out strategy data structure; this means that the
element stored in last will be removed first.
 Stack has specific but very useful applications; some of them are as
follows:
– Solving Recursion - recursive calls are placed onto a stack, and
removed from there once they are processed.
– Evaluating post-fix expressions
– Solving Towers of Hanoi
– to move an entire stack of disks from the
source position to another position.
– Backtracking
– Depth-first search
– Converting a decimal number into a binary number
Data Structures and Algorithms - CoSc2091 60
Some important DS: Queue
 Queue is a first-in-first-out data structure.
 The element that is added to the queue data structure first, will be
removed from the queue first.
 Dequeue, priority queue, and circular queue are the variants of
queue data structure.
 Queue has the following application uses:
 Access to shared resources (e.g., printer)
 Multiprogramming
 Message queue

Data Structures and Algorithms - CoSc2091 61


Some important DS:Trees
 Tree is a hierarchical data structure.
 The very top element of a tree is called the root of the tree.
 Except the root element every element in a tree has a parent element,
and zero or more children elements.
 A tree is a nonempty collection of vertices and edges that satisfies
certain requirements.
 A vertex is a simple object (also referred to as a node) that can have a
name and can carry other associated information;
 an edge is a connection between two vertices.

Data Structures and Algorithms - CoSc2091 62


Some important DS: Heap
• Heap is a binary tree that stores a collection of keys by satisfying heap
property.
• Max heap and Min heap are two flavors of heap data structure.
• The heap property for max heap is: each node should be greater than or
equal to each of its children.
• While, for min heap it is: each node should be smaller than or equal to
each of its children.
• Heap data structure is usually used to implement priority queues.

Max-heap Min-heap

Data Structures and Algorithms - CoSc2091 63


Some important DS: Hash Table
 Hash Table is again a data structure that stores data in form of key-
element pairs.
 A key is a non-null value which is mapped to an element.
 And, the element is accessed on the basis of the key associated with it.
 Hash table is a useful data structure for implementing dictionary.
 Hashing is the process of converting a key
into an index that can be used to access
the corresponding value in the hash table.
typedef struct {
char* key;
int data; key data
} Pair;

Data Structures and Algorithms - CoSc2091 64


Some important DS: Graph
 Graph is a networked data structure that connects a collection of
nodes called vertices, by connections, called edges.
 An edge can be seen as a path or communication link between two
nodes.
 These edges can be either directed or undirected.
 If a path is directed then you can move in one direction only, while in an
undirected path the movement is possible in both directions.

// Define a struct to represent the graph


typedef struct {
// Number of vertices in the graph
int numVertices;
// Adjacency matrix to store edges
int adjMatrix[MAX_VERTICES][MAX_VERTICES];
} Graph;

Data Structures and Algorithms - CoSc2091 65


Why Data Structure?
• To solve problem of real world data storage, in sorting, storing, searching,
deleting and so on.
– Real-world data means data that describes physical entries external
to the computer.
– E.G. – Personnel record, Inventory record, Stack of index cards.
• Used as tools to facilitate some other operation by programmer ( they
help execute an algorithm)
– E.g. stacks, queues and priority queues.
• Those structures are accessed by the program itself not by users

Data Structures and Algorithms - CoSc2091 66


Why Data Structure?
 To directly model a real-world situation.
 For instance
– Graph, which used to represent routes between locations, Telephone
cable in city
 Connections in an electrical circuit or task in project.
 Stacks, queues, and priority queues used in simulations
 Queues can model customers waiting in line at a bank
 Allows major improvements in program efficiently.

Data Structures and Algorithms - CoSc2091 67


Assessment
 Differentiate between a queue and a stack data structures.
 Define linear data structures and give an example.
 List out the basic operations that can be performed on a stack.
 Briefly state the difference between queues and linked lists.

Data Structures and Algorithms - CoSc2091 68


Next: Algorithms Analysis

Data Structures and Algorithms - CoSc2091 69

You might also like