0% found this document useful (0 votes)
18 views15 pages

Data Structure Notes 1ST Sem

The document provides an overview of data structures and algorithms, focusing on abstract data types such as linked lists, stacks, queues, and trees. It explains the characteristics and operations of these data structures, as well as algorithm design paradigms like divide and conquer and dynamic programming. Additionally, it compares linked lists and arrays, and details various operations and applications of stacks and queues.

Uploaded by

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

Data Structure Notes 1ST Sem

The document provides an overview of data structures and algorithms, focusing on abstract data types such as linked lists, stacks, queues, and trees. It explains the characteristics and operations of these data structures, as well as algorithm design paradigms like divide and conquer and dynamic programming. Additionally, it compares linked lists and arrays, and details various operations and applications of stacks and queues.

Uploaded by

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

DATA STRUCTURES AND

ALGORITHMS NOTES (1ST SEM) Abstract Data Types:


Linked list is used for storing elements
where each is a separate object.
Stack is an ordered list in which
PRELIMS insertion and deletion are done at one
(1) end.
Fundamentals of Data Structure and o Stack – an ordered list in which the
Algorithms last element added is the first element
retrieved or removed (Last-In, First-
Out).
Data structure - is a special format for
storing and organizing data. Queue is an ordered list in which
insertion and deletion are done at
Two (2) types of data structure: separate ends.
◦ Linear: Elements are accessed in a o Queue – an ordered list in which the
sequential order but may be stored first element added is the first element
unsystematically. retrieved or removed (First-In, First-
◦ Non-Linear: Elements are stored and Out).
accessed in a non-sequential order.
Tree represents a hierarchical nature of
a structure in a graphical form.
An abstract data type (ADT) is a logical
description of how data is viewed as
Priority queue - is used for retrieving
well as the operations that are allowed
and removing either the minimum or
without regard to how they will be
maximum element.
implemented
- a special type of queue where
elements are processed based
Benefits of using ADT:
on their order (natural or custom).
◦ Code is easier to understand.
◦ Implementations of ADTs can be
Heap is a partially sorted binary tree.
changed without requiring changes to
– a complete binary tree where the
the program that uses the ADTs. value of each of each parent node is
◦ ADTs can be used in future programs. either higher or lower than the value of
its child nodes.
Two (2) parts of ADT:
Set represents a collection of elements
◦ Public or external – the data and the that do not have to be in order.
operations -o a collection of elements where each
◦ Private or internal – the representation element is unique.
and the implementation
Map is a set of ordered pairs with
elements known as keys(identifiers) and Elements of an algorithm:
value(content) .
Sequential operations
Graph consists of a set of points/nodes Actions based on the state of a data
(vertices) and set of links (edges) which structure.
connects the pairs of vertices.
- o consists of a set of vertices Iteration – repeating an action multiple
(or nodes) and a set of edges times.
(relations) between the pairs of
vertices.
Recursion – when a function calls itself
once or multiple times to solve a
The four (4) main operations that could problem.
be defined for each ADT are initializing,
adding, accessing, and removing of Algorithm design paradigms:
data.
Divide and Conquer – breaking a
Algorithm is a step-by-step set of problem into smaller subproblems.
instructions to be executed in sequence - A problem is broken into smaller
subproblems.
for solving a problem.

Characteristics of an algorithm: Greedy Algorithms – always chooses


the optimal approach in solving a
Finiteness: An algorithm must terminate problem.
after a specified number of steps. -The optimal approach is always chosen
in solving a problem.
Definiteness: Each instruction has to be
clear and unambiguous. Dynamic Programming – similar to
divide and conquer except that the
Input: An algorithm should have zero or results of the subproblems are reused
more well- defined data given before the for overlapping subproblems.
algorithm begins.

Output: An algorithm must have one (1) LINKED LIST


or more results, with specified relation to ■ A linked list is used for storing a
the input. collection of data where each element is
a separate object.
Uniqueness: The result of each step ■ Elements in a linked list are called
depends on the input and/or the result of nodes.
the previous step ■ The parts of a node are the following:
– Search – finds a specific element in
the list
– Count – returns the number of
– Data field –This contains the value of elements in the list
the element.
– Pointer field (link or reference) –This Linked List versus Array
contains the address (random memory
location) of the next node. ■ Iteration is the process of repeating a
set of instructions. This is also known as
Linked List Basics “looping”
■ The next node in the list is referred to
as the successor.
■ The first node in the list is called head. LINKED LIST ARRAY
■ The last node points to null since
Number of elements Number of elements
there are no more successive elements.
can expand is fixed upon creating
the array

It can grow and shrink Array size is specified


during program during declaration
execution
■ A linked list is illustrated by:
The position of the The position of
elements is allocated elements is allocated
– Placing the address of the node above during runtime. during compilation
its data field. Elements are Elements are
sequentially accessed randomly accessed.
– Placing the address of the next node
It utilizes memory Memory utilization is
in the node’s pointer field. efficiently ineffective

– Indicating null in the pointer field of


Types of Linked List
the last node.
■ Singly linked list – the basic linked list
– Connecting the previous node to the
next node using an arrow to the right. ■ Doubly linked list – contains an extra
pointer to connect to the previous node
■ Operations of a linked list: in the sequence. The left pointer
contains the address of the preceding
– Display – shows the elements in the node called “predecessor.”
list
– Insert – adds an element into the list

– Delete – removes a specific element


or all the elements from the list
■ A doubly linked list is illustrated • FOLLOWS THE PRINCIPLE FI-FO
by: (FIRST IN – FIRST OUT) which is
– Placing the address of the node tinatawag rin na first come first serve,
above its data field IKAW ANG UNA
– Placing the address of the preceding
node in the node’s left pointer field • LI-LO (LAST IN – LAST OUT) since
ikaw yung huling nakapila ikaw yung
– Placing the address of the next node huling makakaalis sa pila
in the node’s right pointer field
• May limitataions Queue Data Structure
– Indicating null in the left pointer field of is that empty spaces will not filled again
the first node and in the right pointer until the queue is empty. Pag
field of the last node. nabawasan ng isa bawal pa magdadag
need muna na ubusin bago magpapila
ulit
■ C ircular linked list is a linked list in
which the last node’s right pointer
contains the address of the first node. • FRONT REAR NAKATURO SA -1

• FRONT SYA yung nag iidecate kung


nasaan yung harap ng pila, yung REAR
sya yung nag iindicate kung nasaan
yung likod nung pila

QUEUES (PILA) • FULL QUEUE - malalaman lang natin


kapag full queue kapag yung rear natin
• A queue is an ordered list in which the ay nasa pinaka dulo na index na
first element added is the first element
retrieved or removed (First-In, First- • DEQUEING – yung front mamomove
Out). na sya. Bawal na lagyan ng value yung
pinagpilahan na ng una. Hagga’t hindi
• The first element in the queue is pa ubos ang pila hindi malalagyan ng
known as the head of the queue. bagong element yung ating queue need
talagang maubos.
OTHER REFERENCES:
• LOGIC NG QUEUE: Need talaga na
• QUEUE – IN TAGALOG PILA maubos ang pila bago magpapila ulit.

• QUEUE DATA STRUCTURE - yung QUEUE OPERATION:


data structure natin ay nakapila
• enqueue (x) – Inserts data in the rear interfaces cannot be instantiated,
of the queue. Mag iinsert tayo ng data LinkedList is used to instantiate a
sa likod ng pila need ng parameters. Queue object.
Parang push
• The methods of collections.deque are
• dequeue () – Remove data on the front used to implement queues in Python.
of the queue. Mag reremove lang tayo The import statement shall be from
ng data sa harapan ng queue natin kasi collections import deque.
tapos na
• The list methods can also be used to
• isEmpty() – checks if queue is empty – implement queues in Python/Java
ichecheck nya lang kung yung queue is
walang laman FIFO OF QUEUES

• isFull ()- Checks if queue is full – • Empty queue - No elements are


ichecheck nya lang kung yung queue present inside of the storage
natin ay full na
• Enqueue - Adding/putting/inserting
• peek() – returns the data at the front of element to the end of the queue.
the queue. Ang kinukuha dito ay front
data nung queue kung sino yung nasa • Dequeue - Removing the elements
harap sya yung kukuhanin from the front of the queue

• size()- returns the size of the queue. • IsEmpty - Check if the queue is
Binabalik nya lang yung suze ng queue empty.
natin, ilan yung lamang ng pila natin as
of the moments. • IsFull -Check if the queue is full

• Peek - Get the value of the front of the


(PPT NOTES ABOUT QUEUE): queue without removing it.

Queues are used in any of the following: WORKING ON QUEUE


• CPU and disk scheduling • Front - Track the first element of the
• Serving requests on a single shared queue
resource, such as a printer
• Managing customers trying to get hold • Rear - Track the last element of the
of a hotline. queue

• The methods of the Queue interface THE TWO MAIN QUEUE OPERATION
from the java.util package are used to
implement queues in Java. Since Method in Java:
• offer() Queue queue = new
LinkedList(); Functions Java Python

Delete all clear() clear()


• queue.offer("Lisa");
elements

Method in Python: Copy all clone() copy()


elements
• append() queue = deque([])
return size() len()
• queue.append("Jennie") length/size

Reverse the Collections.rever reverse()


• Dequeue – removes the head of the elements se()
queue • Method in Java: poll()
MIDTERMS
• Method in Java: popleft() STACKS

OTHER QUEUE OPERATIONS A stack is an ordered list in which the


last element added is the first element
Method in Java: peek() retrieved or removed (Last-In, First-Out).

• Syntax in Python: queue_name[0] OTHER REFERENCES:

• Test whether queue is empty STAKS DATA STRUCTURE


- MAEANING magkakapatong patong
• For Java, use the isEmpty() method. yung data natin It follows the
• For Python, use the if not condition, principle:LI-FO (LAST IN, first OUT) –
followed by the queue name and a kung ano yun huling pumasok sya ang
colon. unang lalabas

• Example: queue = deque([]) if not FI-LO (FIRST IN, LAST OUT) – kung
queue: print("Queue is empty.") ano yung unang pumasok, sya ang
huling lalabas
OTHER QUEUE METHODS
STACK OPERATION
• Java methods offer(), poll(), and peek() Push()- Inserts data on top of the stack
do not throw exceptions. The methods – magdadagdag ng data sa top ng stack
add(), remove(), and element() perform nagpataong lang
the same tasks but throw exceptions. Pop()- Removes data on top of the stack
– nag dedelete tayo ng data sa taas ng
• Other methods that can be used for stack, aalsin lang natin yung data sa
both queues and lists are the following: pinakataas
isEmpty() – Checks if stack is empty – - Push - adds an item to the top of
chinecheck nya lang kung walang the stack
laman. Pag negative 1 ang top index - Pop - removes an item from the
meaning walang laman top of the stack
- Peek - looks at the item at the top
isFull() – checks if stacks is full – of the stack without removing it
chinecheck lang if puno na yung stack. from the stack.
Nasa pinakataas ng index natin
Stack Applications
Peek () – returns the data at the top of
the stack. Kung anong data yung nasa Finding palindromes:
taas ng stack natin currently irereturn
yun. ◦A palindrome is a string that reads the
same in either direction.
Size() – returns the size of the stacks.
Ilan ang value na nasa loob ng stack. ◦ Ex. level, radar, civic Evaluating a
postfix expression:
PPT NOTES:
◦A normal expression is in infix notation.
Fundamentals
◦In a postfix expression, the operands
•During program execution, the stack (variable or number) precede the
can be used to store information about operators (symbol).
the parameters and return points for all
the methods that are currently INFIX example: (yung maayos na
executing. expression)
- A+B
•Stacks are used by compilers to store - A+B*C
information while evaluating
POSTFIX example : (hindi nakaayos yung
expressions.
expression)
- AB+
•The methods of the Stack class from - ABC*+
the java.util package are used to
implement stacks in Java.
Rules of INFIX:
The list methods are used to implement Algorithm:
stacks in Python.
1. Classify the token (operand or operator).

The two (2) main stack operations are 2. If token is an operand, push it to the stack.
the following:
5. Repeat Steps 1 to 4 until the last
3. If token is an operator, perform two (2) pop token.
operations.

6. If there are no more tokens, pop all


4. Perform the operation on the two (2)
popped operands based on the operator. the operators and append to the postfix
Push its result to the stack. expression

5. Repeat until the end of expression.


EXAMPLE OF INFIX:
RULES OF POSTFIX

Converting from infix to postfix


Algorithm:

1. Classify the token (operand or


operator).

2. If token is an operand, append it to


the postfix expression.

3. If token is an operator,

◦ push it to the stack if stack is empty or


has higher precedence than the
operator on the top of the stack.
Example of Converting from INFIX TO
POSTFIX
◦ If it has lower or equal precedence,
pop the operator from the top of the
stack, append it to the postfix
expression, and push the current
operator to the stack.

4. If a right parenthesis is encountered,


pop all the elements until a left
parenthesis is encountered. Append all
these elements to the postfix expression
except the parentheses.
MIDTERMS have children are known as internal
nodes.
TREE FUNDAMENTALS
Tree as Subtree
• A tree represents a hierarchical nature
of a structure in a graphical form. It • tree within a tree is considered a
consists of elements or nodes, with subtree.
each node linked to its successors. • The level of a node is a measure of its
distance from the root.
• The best example of a tree is the • The depth of the tree is its highest
computer's file system: C:\Users\bpena\ level. • The degree is the number of
Desktop\TreeDemo.java child nodes in a subtree.
• The top of a tree is called its root. The
links from a node to its successors are
called branches, edges, lines, or paths.

• The top of a tree is called its root. The


links from a node to its successors are
called branches, edges, lines, or paths.

• The successors of a node are called its


child nodes or children. The
predecessor of a node is called its
parent.

NODES

• A tree is considered a binary tree if all


its nodes have two (2) child nodes at
most.

• Each node in a tree has exactly one


(1) parent except for the root node,
which has no parent.

• Nodes that have the same parent are


siblings.

• A node that has no child nodes is a


leaf node or external node. Nodes that TREE TRAVERSAL
• Traversal is the process of visiting all node by adding it to the end of that
the nodes in a specific order. node's child array.

• The following are the different traversal • Other Java methods used in retrieving
types: values from a tree are:

• Depth-First

• Inorder (Left, Root, Right): 4, 2, 5, 1, 3


Start with the bottommost left subtree.
Once the root in Level 0 is visited,
proceed to the bottommost right
subtree.

• Preorder (Root, Left, Right): 1, 2, 4, 5,


3 Start with the root in Level 0 then
continue with the left subtree.

• Postorder (Left, Right, Root): 4, 5, 2, 3,


1 Start with the bottommost left subtree
then proceed to the other subtrees. The
root in Level 0 is the last node visited.

Programming Trees

• The JTree is a Java Swing component


that displays a set of hierarchical data
as an outline. It is included in the
javax.swing package.

• The Java class,


DefaultMutableTreeNode, is used to
represent a general-purpose node in a
tree data structure. It is included in the
javax.swing.tree package.

• The add() method removes a node


from
its parent and makes it a child of
another
SAMPLE CODES
either higher or lower than the value of
• To create an empty tree its child nodes
- JTree tree = new JTree();
TYPES OF HEAPS
• To create a node:
- DefaultMutableTreeNode root = • Min Heap – The value of each parent
new node is less than or equal to the values
DefaultMutableTreeNode("B"); of its child nodes.

• To create a tree with identified root • Max Heap – The value of each parent
node: node is greater than or equal to the
- JTree tree = new JTree(root); values of its child nodes.

• To add a child node


- root.add(n1); //n1 is another node
BASED SA YT
• To display the children of a node:
- //Convert the Enumeration type • MAX-HEAP – EVERY CHILD HAS TO
to List BE SMALLER THAN ITS PARENTS,
- List childNodes = SO EACH PARENT NODE HAS TO BE
Collections.list(root.children()); LARGER THAN ALL OF ITS CHILDS
System.out.print(childNodes);
- //or simply • MIN-HEAP – PARENTS IS ALWAYS
- System.out.print(Collections.list(r SMALLER KESA SA CHILDREN
oot.children()))
• PRIORTY QUES- ELEMENTS GET
• To display a traversed tree: PROCESSED BASED ON THEIR
PRIORTIES. THE LOWEST NUMBER
- //Convert the Enumeration type MEANS THE HIGHEST PRIORTY OR
to List THE LARGEST NUMBER MEANS IT’S
- List preTree = HIGHEST PRIORTY.
Collections.list(root.preorderEnu
meration()); • HEAPIFY – UP OPERATION –
System.out.print(preTree); WHICH MEANS PUNTA KA SA ISANG
ELEMENT TAPOS IPAGKUKUMPARA
MO SYA SA PARENTS EXAMPLE: 3 IS
HEAPS LESS THAN 92 THAT VIOLATES THE
HEAP PROPERTY SO IPAG SSWAP
• A heap is a complete binary tree where MO SILA. 92 Yung Magiging parents
the value of each of each parent node is then yung 3 yung magiging anak (LEFT)
HEAPS •Peek (Find max/min)

•Heaps can be implemented in Java HEAPIFY


using ArrayList from the java.util •Heapify is the process of creating a
package. heap data structure from a binary tree. It
•Example: ArrayList heap = new is used to create a Min-Heap or a
ArrayList<>(); MaxHeap.

• To create a heap with initial values,


use the addAll() method of the PEEK (FIND MAX/MIN)
Collections class (also from the java.util
package). • Peek operation returns the maximum
element from Max Heap or minimum
• Example (based on the given min heap element from Min Heap without deleting
above): the node.
• ArrayList minHeap = new
ArrayList<>(); • For both Max heap and Min Heap.

• Collections.addAll(minHeap, 1, 7, 6, 8, EXTRACT-MAX/MIN
9); • Explanation: The root node is
always at index 0. Its child nodes are •Extract-Max returns the node with
always at index 1 and index 2. Indices 3, maximum value after removing it from a
4, 5, and 6 can store the child nodes of Max Heap whereas Extract-Min returns
those two (2) nodes and so on. the node with minimum after removing it
from Min Heap

HEAPS
PRIORTY QUEUES
•To determine the root node, use the
get() method. • A priority queue is a special type of
queue where elements are processed
•Example: based on their order (natural or custom).
System.out.print(minHeap.get(0));
• Priority queues can be implemented in
HEAPS OPERATIONS Java using the PriorityQueue class from
the java.util package.
•Heapify – PAG SSWAP
•Insert Element into Heap • Example:
PriorityQueue printer = new
•Delete Element from Heap PriorityQueue<>();
•Peek (Find max/min)
▪ A set is a collection of elements where
each element is unique.
BROCODE YT
▪ Common set operations:

▪ Union: The union of two (2) sets (A ∪


• PRIORTY QUEUE – FIFO DATA
STRCUTURE THAT SERVES
ELEMENTS WITH THE HIGHEST B) is the set that contains all the
PRIORTIES FRIST BEFORE elements in either set.

▪ Example: {1, 3, 5, 7} ∪ {2, 3, 4, 5} = {1,


ELEMENTS WITH LOWER PRIORITY

• SMALLER TO LARGE NUMBER 2, 3, 4, 5, 7}

• QUEUE QUEUE = NEW ▪ Intersection: The intersection of two (2)


PRIORTYQUEUE<>(); - SMALLER TO sets (A ∩ B) is the set that contains only
HIGH NUMBER the elements common to both sets.

• QUEUE QUEUE = NEW ▪ Example: {1, 3, 5, 7} ∩ {2, 3, 4, 5} = {3,


PRIORTYQUEUE<>(COLLECTION.RE 5}
VERSEORDER()); - REVERSE ORDER
▪ Difference: The difference of sets A
Priority Queues and B (A – B) is the set that contains the
• To enqueue, use add() or offer(). To elements that are in A but not in B.
dequeue, use poll() or remove(). The
dequeue operation starts with the ▪ Example: {1, 3, 5, 7} – { 2, 3, 4, 5} = {1,
minimum element. 7}

Priority Queues ▪ Subset: Set A is a subset of set B (A ⊂


B) if every element of set A is also an
• A comparator is used to create a element of set B.
specific ordering for a collection of
objects. ▪ Example: {1, 3, 5, 7} ⊂ {1, 2, 3, 4, 5,
7} = true
• To create a comparator in Java, use
the Comparator interface and its JAVA Sets
methods such as comparing(),
comparingInt(), and compare(). ▪ A collections framework provides
mathematical set in JAVA.
SETS AND MAPS SETS
▪ Add() - elements
SETS
▪ addAll() – all elements in one set / ▪ TreeSet – This stores its elements in a
UNION special type of tree where elements are
sorted (natural or custom) during
▪ Iterator() – returns am iterator that can iteration.
be used to access elements of the sets
sequentially. ▪ LinkedHashSet – This stores its
elements in a hash table with a linked
▪ Remove() – remove the specific list running through it. The order of the
elements from the set elements during the iteration is the
same as the order they were inserted
▪ Removeall() – all the elements from into the set.
the set
▪ EnumSet – a map implement for
▪ retainAll() – retains all the elements elements

▪ Clear() – remove all the elements from Maps


the set
▪ A map is a set of ordered pairs where
▪ Size() – returns the length of the set elements are known as keys (identifiers)
and values (content).
▪ Contains() – return true if the set
contains the specific element ▪ A map cannot contain duplicate keys.

▪ containsALL – return true if the set ▪ Each key can map to only one
contains all the elements of the
specified collection
Maps Interfaces
▪ hashCODE() – hash the code value
▪ Sorted Map

▪ Sorting of keys stored in a map 🡪


3 - general-purpose set implementations TreeMap

▪ All are included in the java.util ▪ Navigable Map


package. ▪ It provides features to navigate among
▪ HashSet – This stores its elements in a the map entries.
hash table without a guaranteed order
upon iteration. This is the best- ▪ TreeMap
performing implementation. ▪ headMap(Key, booleanValue) 🡪
ceilingEntry(), ceilingKey()
▪ tailMap(Key, booleanValue) 🡪
floorEntry(), floorKey()

▪ subMap(K1, BV1, K2, BV2)

▪ Concurrent Map

▪ It provides a thread-safe map. Multiple


threads can access the map at once w/o
affecting the consistency of entries in a
map

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