Description:
Lecture 2: Expressions, Variables, Operators, Assignments, and Statements
Program Organisation
- File name must be as same as class name
- A Java program needs to start its execution from the main method of some class
Variable types:
- Local variables: variable declared inside a method
- Parameters: variable that is passed to a method when the method is called/executed.
- Primitive vs reference variable
-
Primitive values:
```java
byte //1 byte short //2 bytes int //4 bytes long //8 bytes float //4 bytes double //8 bytes char //2 bytes boolean //1 bit
-
Referent variable:
-
Statements
-
A statement is a complete unit of execution that performs a specific action (end with’;’). For example:
-
The System is a class, out is the object of PrintStream class.
-
The println() is the method of PrintStream class which displays the result and then moves the cursor to the next line
-
Declaration:
int a = 10;
-
The if…else Statement
-
The switch Statement
-
The while Loop
-
The do…while Loop
-
The for Loop
-
For each loop:
-
Enhanced for loop in Java
-
The break Keyword
-
The continue Keyword
String Concatenation
System.out.println(str1.concat(str2));
System.out.println(str1+str2);
System.out.println(str1 += str2); // all the same
String Methods
String s = "hello it is me";
String[] words = s.split(" ");
double length = Double.parseDouble("1.5");
Postfix/Prefix in/decrement
Java Type Casting
- Java supports two types of casting:
- Widening Casting (Implicit): done automatically by Java when we assign a value of a smaller data type to a variable of a larger data type. For example:
int x = 10;
double y = x; // Implicit casting from int to double
- Narrowing Casting (Explicit): done manually by the programmer when we assign a value of a larger data type to a variable of a smaller data type. For example:
- Parsing:
- To int:
int j = Interger.parseInt(s);
- To int:
Getting Inputs
- Important to instantiate new Scanner object
Scanner input = new Scanner (System.in);
- import the scanner first
import java.util.Scanner;
- important to close the object
- import the scanner first
- Also, close scanner object when done
Lecture 3: Program Structure, Organization, and Modular Programming in Java
OOP:
- Abstraction: a process of hiding the implementation details from the user
- Abstract Data Type (ADT): a special data type that is defined by a set of values and a set of operations on that type
- Encapsulation: a process of binding data and functions together into a single unit such that they are kept both safe from outside interference and misuse
- Make the instance variables private so that they cannot be accessed directly from outside the class, only through
getter()
andsetter()
methods in the class to set and get the values of the fields
- Make the instance variables private so that they cannot be accessed directly from outside the class, only through
- Inheritance: a process by which one class takes on the attributes and methods of another
- super class: the class that child classes are derived from
- sub class : newly formed class that can override or extend the attributes and methods of parent classes
- Polymorphism (“many forms”): the ability of programming languages to present the same interface for differing underlying data types.
Program Structure
Packages
-
A Java program is typically organized into packages. A package, written in lowercase, is a collection of related classes
- We declare the package name in which the class is placed
- It must be defined before any class and interface declaration
- Only one (1) package statement in a Java program.
Import
- If we want to use any class of a particular package, we need to import that class.
- The import statement is used to represent the class stored in the other package
Interface
-
Interface section contains only static constants and abstract method declarations which cannot be instantiated, no constructor
-
An interface is a completely abstract class that is used to gather related methods (with empty bodies) for two objects to interact
-
To access the interface methods, the interface need to be implemented by another class with the implements keyword.
-
When a class implements an interface, it must implement all of the methods declared in the interface!
-
Interface’s methods with body only with default keyword
Lecture 4: Strong Typing, Classes, Objects, and Exceptions
Classes
- A Java program consists of one or more classes. A class is a blueprint for creating objects that have similar attributes and behaviors. For example:
Class variable (static field)
-
Variable that belongs to a class.
-
The static variables can be get and set in program thru objects
-
They are common to all instances of that class, i.e., changes made to class variables by one object will reflect in all objects.
- Preferably to use class’s variable
Object variable (instance fields)
-
Variables that belongs to an object
Constant variables
-
Constant is used in Java when a static value or a permanent value(never change from the initial value) for a variable has to be implemented
- Use
static
andfinal
access modifier to implement - Conventionally all capital
- Use
Abstract class
- Only meant to be inherited (extends), not instantiate
- May or may not contain abstract methods
- Can contain normal methods too
- Inherited classes must implement abstract methods if included
Abstract methods
- Must be empty and be inside an abstract class
- If inherited by a normal class, that class must be override abstract methods
- Abstract class can inherit another abstract class without implementation abstract methods
Objects
- An object is an instance of a class
Exceptions
-
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. In Java, exceptions are handled using try-catch blocks. Common scenarios are:
- Invalid data in the input
- Cannot open file
- Network connection
- JVM run out of memory
-
Types of exceptions:
- Checked exceptions (compile time exceptions): checks by the compiler, e.g., network connection, missing file,..
- Unchecked exceptions (runtime exceptions): occurs at the time of execution, e.g, programming bugs such as logic errors or improper use of an API,..
- Errors: problems that arise beyond the control of the user or the programmer, e.g., stack overflow, out of memory,…
-
Strong Typing
Strong typing is a programming language feature that ensures that variables are used only in ways that are consistent with their declared types. For example:
int x = 5; String s = "Hello, world!"; int y = x + s; // This will result in a compile-time error
In this example, the variable
y
is assigned the value ofx + s
, which is not allowed becausex
is anint
ands
is aString
.
Java access-modifiers
“this” keyword
this
can be used to:-
refer current class instance variable.
-
invoke current class method (implicitly).
-
invoke current class constructor (constructor chaining)
-
be passed as an argument in the method call.
-
be passed as an argument in the constructor call.
-
used to return the current class instance from the method.
-
Lecture 5: Java Constructors and Inheritance
Constructors
-
A constructor method, same name with class, is a special method that is used to initialize objects, called whenever an instance is created
-
Default constructor
- It is generated automatically if not implemented
-
Parameterized constructor
Constructor overloading
-
this() reference:
- Must be the first statement inside a constructor
Initializer blocks
- Multiple static blocks will execute in order
- Static initialization block: runs when the class is loaded into memory, before any instances of the class are created. This block is used to initialize static variables.
- Initialization block: runs when an instance of the class is created, before the constructor. This block is used to initialize instance variables.
- Constructor: runs when an instance of the class is created. It is used to set the initial state of the object and can take parameters to initialize instance variables.
Inheritance
- Inheritance is a programming technique that allows a class to inherit attributes and methods from another class. Keyword
extends
- Multiple and Hybrid are supported through interface only
-
Multiple inheritance
-
Hybrid inheritance
-
Lecture 6: Static Classes and Members
Instance variable
- Declared in a class but outside of any block, method or constructor.
- Accessible to all the constructors, blocks and methods in the class.
Static variable
- A static class is a class that cannot be instantiated and is used only to provide static methods and attributes
- Can be accessed without an object
- Can be reassigned with an object, but it will change the value for all other instances
Instance method
- An instance must be created to be used
Static method
- Call directly from class without an instance
ClassName.StaticMethodName()
Static class
- Cannot be instantiated and is used only to provide static methods and attributes
- Static methods and attributes can be accessed without creating an instance of the class as long as access is granted
- Can not call instance methods or access instance variable
Nested class
-
Non-static nested classes (inner classes):
-
Have access to other members of the enclosing class (even if they are declared private)
-
Inner class cannot define any static member
-
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object.
-
-
Static nested classes:
- Cannot access to other members of the enclosing class
- Inner class can be declared private, public, protected, package private while outer class can only be declared public or package private
Java anonymous inner class
- A local class without a name, which is used to declare and instantiate a class at the same time
- It is often used to create an object that implements an interface or extends an abstract class without having to define a separate class for it
- Often used for GUI applications
- Keyword
@Override
Recursion
Lecture 7: Polymorphism
Method Overloading
- Like constructor overloading, it create multiple methods with the same name but with different parameters or argument types
- It is performed within class
- When you call an overloaded method, Java matches the method call to the correct method based on the number and types of arguments. To overload, we can change:
- Number of args
- Arg datatype
- Both number of args and arg datatype
Method Overriding
- When a subclass has the same method signature (name, parameters list, return type) as declared in the parent class, the subclass redefine that method, provide a specialized version
- The overridden method must have the same access modifiers (public, private, protected) and return type as the original method. The subclass can have a more permissive access modifier for the overridden method, but not a more restrictive one.
Static method hiding
- When overriding static methods in inheritance
- If a subclass defines a static method with the same signature as a static method in the parent class, the static method in the parent class is hidden.
- The version getting invoked depends on whether its invoked from superclass or subclass, not the object itself
Types of Polymorphism
There are two types of polymorphism in Java:
- Static polymorphism: resolved at compile time
- Method Overloading
- Dynamic polymorphism: resolved at runtime
- Method overriding
Class vs Abstract Class vs Interface
In Java, you can create three different types of classes:
- Class: A blueprint for creating objects. It can contain instance variables, constructors, methods, and static variables and methods.
- Abstract class: A class that cannot be instantiated but can be subclassed. It can contain instance variables, constructors, methods, and abstract methods. Abstract classes are useful when you want to provide a common interface for a group of related classes.
- Interface: A collection of abstract methods and constants. It defines a contract that a class must implement. A class can implement multiple interfaces, but can only extend one class. Interfaces are useful when you want to create a common interface for a group of unrelated classes.
Lecture 8: Lists as Data Structures, Collections, Iterators, and Generics
Collection interface
- A collection is a group of objects that can be treated as a single unit. In Java, collections are implemented using the
Collection
interface - Can do searching, sorting, inserting, …
- e.g: java.util.Collection;
March 9, 2023 4:00 PM rewrite properties and methods from each class
Array | List | ArrayList |
---|---|---|
A fixed-size data structure | A dynamic-size data structure | A dynamic-size data structure |
Can hold only elements of the same data type | Can hold elements of different data types | Can hold elements of different data types |
Requires explicit memory allocation | Automatically allocates memory | Automatically allocates memory |
Elements can be accessed using an index | Elements can be accessed using an index | Elements can be accessed using an index |
Cannot be resized once created | Can be resized dynamically | Can be resized dynamically |
Can be multidimensional | Can be implemented as a single-dimensional or multidimensional collection | Can be implemented as a single-dimensional or multidimensional collection |
Basic functionality in java | Part of the Java Collections Framework | Part of the Java Collections Framework |
Array
-
Fixed size static data structure
List Interface:
-
Found in java.util package, inherited from collection interface
-
Unlike array, list allows you to add and remove elements after created, even resize the list
-
ListIterator interface
: allow us to iterate the list forward and backward -
Commonly used list methods:
ArrayList class {}
-
import java.util.ArrayList;
, a part of Collection framework -
ArrayList is a data structure that stores a collection of elements of the same type in a particular order as a single variable in Java
-
A list is a data structure that stores a collection of elements of same type in a particular order as single variable. In Java, lists are implemented using the
List
interface -
The Contructor argument can be:
-
List<String> names = new ArrayList<String>();
Creating a list: []
List view of array
-
Arrays.asList()
and pass the array argument to ArrayList constructor to initialize an arraylist in single line statement -
List.of()
static factory methods to create immutable lists. Only drawback is that add operation is not supported in these listsimport java.util.List;
Java Iterator
- Belongs to collection framework
- Traverse a collection of elements, access and remove data elements like a pointer
- Iterator starts before the value, here
import java.util.Iterator;
- Methods:
-
here.next()
returns the next element moves the iterator after that (after 15) -
here.remove()
removes the element behind it -
here.hasNext()
returns true if there is another element after it
-
Java ListIterator
- extends of Java Iterator
- import
java.util.ListIterator;
- Methods
here.previous()
returns the previous element of the listhere.previousIndex()
returns the index of the element that theprevious()
will returnset()
replaces the element returned by either next() or previous with the specified element
LinkedList
- extends Abstract SequencialList implements Deque
- A linear data structure consisting of a collection of Nodes with any datatype that are not stored in contiguous but random memory locations
- Helps to build even more complex data structures like Stacks, Queues, Skip Lists, etc.
- List grows as per the program’s demand (no resizing problem) and limited to the available memory space
- Each node is a data field, elements are linked using pointers to the memory address of the next node
- Types of LinkedList:
- Singly linked list
- Doubly linked list
- Circular Linked list
Singly LinkedList
- A class Node which has two attributes: data and next where next is a pointer to the next node. Create another class which has two attributes: head and tail
- First node is head, last is tail which has null pointer
Linkedlist Iterator
Convert LinkedList to ArrayList
Convert ArrayList to LinkedList
Generics
-
Generics are a programming language feature that allows types (classes and interfaces) to be parameterized. In Java, generics are implemented using the
<T>
syntax -
Allows more than one type of object to be processed
-
The parameter
T
must be an object type (Integer, Cat), no primitive type like int, double.
Multiple type parameter generic
Lecture 9: Stacks
Stacks (extends Vector)
- A stack is a dynamic data structure that stores a collection of elements in Last-In, First-Out or LIFO order
push
last-in,pop
first-out- Stacks are implemented using the
Stack
class - Supports:
push(e)
: to add item e onto the stackpop()
: to remove an item and returns the topmost item of the stacksize()
: returns the number of items in the stackisEmpty()
: to check if a stack is emptypeek()
: returns the element at the top of the Stack, only showsearch(element)
: return the position of the element from tos (1), -1 means not foundindexOf(element)
: return the index of the element from bottomset(index, element)
get(index)
add(index, element)
: too
- throws
EmptyStackException
if empty
Converting
Error handling with stacks
- Stack underflow: when pop from an empty stack; check by !stack.isEmpty()
- Stack overflow: when push and nb of items reach the stated size, check by !stack.isFull()
Lecture 10: Queue
Queues (implements Queue)
- For LinkedList, elements in the queue are stored internally in a standard linked list data structure
- A queue is a dynamic data structure that stores a collection of elements in First-In, First-Out or FIFO order
push
last-in,pop
first-out- Queue are implemented using the
LinkedList
class-
offer(e)
: enqueue a new element -
poll(e)
: dequeue the top element and return it, return null if empty -
peek()
: returns the first element of the Queue, only show -
isEmpty()
: -
add(e)
-
remove()
: throws exception if empty -
element()
: -
clear()
: clear the queue
-
Iterate through queue
PriorityQueue (extends Queue)
-
Operates like Queue but each item has a priority
-
Stored in a binary heap, so order is different if used remove
-
Only support comparable datatypes
-
Automatically arranged in order, the lowest element first
-
Stores its elements internally according to a Comparator passed to the PriorityQueue or according to their natural order
-
Supports:
- all methods queue has
Comparable Interface
-
Used to order the objects of the user-defined class
-
Found in java.lang package and contains only one method named compareTo(Object)
-
Provides single sorting sequence
User-define comparing queue
Implementation of queue
- Queue can be implemented by Array, Stack or LinkedList
- Approach [A]: remove the element at head position, and then one by one shift all the other elements in forward position. There is an overhead of shifting the elements one position forward every time we remove the first element.
- Approach [B]: remove the element$ from head position and then move head to the next position. The size on Queue is reduced by one space each time
Lecture 11 & 12: Sorting Algorithms
Bubble Sort: O(n^2)
-
Swap the element to the adjacent if it is bigger
Selection Sort: O(n^2)
- Loop through and find the least element then swap it with the item in front of the sorted
Insertion Sort: O(n^2)
- Divide to sorted and unsorted parts and insert the next number to the right position
- Green number is key
- Start with the key as 2nd element
- While bigger than the key, move elements of arr[0..i-1], that are greater than key to one position ahead of their current position
Merge Sort: O(nlogn)
Shell sort: O(n(logn)^2)
- Variation of insertion sort
- Divides the original list into smaller sublists
- Each sublist is sorted using insertion sort
- The sublists are combined using insertion sort
- The last iteration sorts the entire list using insertion sort
- helps reduce complexity
Quick sort: O(n^2)
- Based on the concept of divide-and-conquer, also known as partition-exchange sort
- Divide array into:
- Elements less than the pivot element
- Pivot element (central element)
- Elements greater than the pivot element.
Lecture 13: Trees and Search Trees
Trees
- Implemented using the
TreeNode
class - A tree is a non-linear data structure that consists of nodes connected by edges
- Height, depth of a node
- A node have 1 parent and many children is an internal node
-
Except root node has no parent
-
Leaf, external node has no children
-
Sibling node
-
Binary Tree
- A tree but each node has at most 2 sub trees
- Level has at most nodes
- Full binary tree:
- Every internal node has exactly two child or more
- Number of leaf nodes = Number of internal nodes + 1
- Complete binary tree:
- Every level possible is completely filled
- All nodes are as far left as possible
- Perfect binary tree:
- Full and complete
- All internal nodes has 2 children and all leaf nodes are in the same level
- Balanced binary tree (Height-balanced tree or AVL tree):
- The ’s height of any given node is 1 or less difference than its ’s height
- Degenerate binary tree:
- Every parent nodes has only 1 child node
- Height of tree = nb of nodes
Set interface
- List interface are all indexed collections, while Set objects are not indexed
- Duplicate items are not allowed
- Removal of an object in Set does not require the shift of elements (unlike in ArrayList)
SortedSet (implements Set)
TreeSet (implements SortedSet extends AbstractSet)
-
Duplicate items are not allowed
-
Objects are stored in a sorted and ascending order
-
Does not allow to insert heterogeneous objects
-
Methods:
add()
addAll()
remove()
headSet(Element e)
: returns values that are greater or equal thane
headSet(Element e, bool false)
: returns values are greater than e only
tailSet()
: returns values that are less or equal thane
first()
last()
Binary Tree implementation
- Adding element
- Finding element:
- Delete element:
Binary tree applications
-
Mathematical: using binary tree to represent math expressions
- The nodes are the operators
-
Boolean:
- (True or false) and not false
- Huffman tree:
- 0010100:
- if 0 turn left, if 1 turn right until see a character and repeat
- 0010100:
Binary Search Trees
- Binary tree with ordered and sorted nodes
- Binary search trees are implemented using the
TreeSet
andTreeMap
classes
- Operation:
Insert(E e
): Add an element to the BST by not violating the BST propertiesDelete(E e)
: Remove a given node from the BST. The node can be the root node, non-leaf, or leaf node. Search the location of the given element in the BSTSearch(E e)
: Checks if the tree contains the specified key.
Algorithm for searching a BST: O(n)
- if( left node and right node are null)
- return notfound
- else if(search = node)
- return node pos
- else if(search < node)
- return recursive with leftnode
- else:
- return recurve with rightnode
Lecture 14: Balanced Trees and Algorithms for Tree Traversal
Balanced Trees ( height-balanced true) (AVL tree)
-
Normal BST might become degenerate after inserting many items like 1,2,3,4,5 in order which hurts performance (from O(logn) to O(n))
-
AVL is a self-balanced tree is a tree data structure in which the total left subtrees and right subtrees of any node differ in height by at most one
Red-black tree:
- An BST with rules:
- The root is black
- The children of a red node are black
- There are no two adjacent red nodes (A red node cannot have a red parent or red child)
- Every path from the root to a null node has the same number of black nodes.
Algorithms for Tree Traversal
- Tree traversal refers to the process of visiting each node in a tree data structure exactly once
- Tee traversal is implemented using recursion
- Includes:
- Preorder: visit root node first, traverse , and traverse
- Inorder: traverse , visit root node, and traverse
- Postorder: traverse , traverse , and visit root node last
Lecture 15 & 16: Heaps and Priority Queues
Binary heap
-
A binary heap is a complete binary tree, meaning it is filled a equally as possible
-
The root node of the heap is the maximum ( max heap) or minimum element (min heap)
-
The value of each parent node is less than or equal to its child nodes
-
Not necessarily a BST
-
Every subtree is a heap
-
Root element is at arr[0]
-
For any
i
th root:- its parent is at index
(i-1)/2
- its left child is at
i*2+1
- its right child is at
i*2+2
- its parent is at index
0 | 1 | 2 | 3 | 4 |
---|---|---|---|---|
20 | 26 | 58 | 22 | 38 |
Inserting an element E to a max heap
- Insert to the next free index (if length(arr) is 8 then index for next element is 8)
- While (index is not 0 and value > value of parent)
- Swap with the parent
heapify()
Removing root from the heap
- Swap the root with the last item in the heap (LIH), remove the LIH
- While item LIH has child, and item LIH is larger than either of its child
- Swap item LIH with its smaller child
- Heapify LIH down the heap.
- Until the heap property is restored
Heapify()
- Initialize the root as largest, heapify down the tree
Building a heap from array
- To build a heap from array, find the position of the last non-leaf and perform heapify of each non-leaf upward direction
Last non leaf = Parent of last node = ((n-1)-1)/2
Implement heap with Priority Queues
- Priority queues are implemented using heap structure
Heap sort algorithm: O(n log n)
-
To sorts an array by first constructing a binary heap from its elements
-
Then repeatedly extracts the highest (or lowest) element from the heap until the heap is empty
-
Each extracted element is added to the sorted list
-
The heap is re-built after each element is extracted
-
Heap sort algorithm:
- Build a heap
- Repeat until the heap is empty
- Heapify down the heap
- Extract the root element (the largest/smallest element)
- Replace with the last item in heap
Lecture 17: Introduction to Graphs
Graphs:
- Collection of vertices (nodes) and edges (links) that connect pairs of vertices
Directed vs undirected graph
-
Undirected graph
- Edges have no direction
- An ordered pair where is adjacent (neighbourhood) to and vice versa
- Degrees: number of neighbours a node have
- Handshaking theorem:
- Sum of degrees is twice number of edges
-
Directed graph (digraph):
- Edges have direction
- An ordered pair where is source and is destination
- Degrees:
- In-degree (): nb of edges terminate at
- Out-degree (): nb of edges start at
Complete graph
- , is the simple graph that contains exactly one edge between each pair of distinct vertices
A cycle
- for consists of n vertices and edges
- A cycle for consist of vertices and edges
Path and cycle
-
A vertex is adjacent if there exists an edge to it (from other vertices)
-
Path: a sequence of vertices in which each successive vertex is adjacent to its predecessor
-
Simple path: no repeated vertices
-
Cycle: simple path but last vertex same as first for every vertices
-
Connected graph
-
If there is a path in an undirected graph that connected every vertex to every other vertices
-
Connected
Directed Acyclic Graph (DAG):
-
A DAG is a directed graph that has no cycle and with at least one node with no targets
-
A directed graph can be DAG if it can be topologically ordered, by arranging the vertices as a linear ordering that is consistent with all edge direction
-
Checking if a graph is a DAG:
- If the graph has no nodes, stop. The graph is acyclic
- If the graph has no leaf, stop. The graph is cyclic
- Choose a leaf of the graph. Remove this leaf and all arcs going into the leaf to get a new graph. Repeat
-
No
- Yes
Coloring
- Assignment of colors to the vertices of a graph that no two adjacent vertices have the same color
- while minimize the number of colors (chromatic number)
- Method to color a graph (with vertices order decided):
- Choose the first vertex and color it with color 0
- Choose next vertex and color it with lowest numbered color that has not been colored on any vertices adjacent to it.
- If all adjacent vertices are colored with this color, assign new color
- Repeat step 3 until all vertices are colored
Chromatic number = 3
Planar Graphs
- A graph that can be drawn on a plane without any edges crossing each other
- Kuratowski’s theorem: a graph is planar if and only if it doesn’t not contain a copy of or
Bipartite Graphs
- A graph whose vertices can be colored only using 2 colors
- A complete bipartite graph :
- A graph that has its vertex set partitioned into two subsets (size m) and (size n) such that there is every edge from to
Lecture 18: Graph presentation
Adjacency matrix
- A square matrix used to represent a finite graph
- Is always symmetric for undirected graph
Adjacency list
- A representation of graph as an array of linked list, each linked list represents the list of vertices it can go to
- The edge between 2 vertices is denoted by a pointer from source vertex to destination vertex
Null pointer if it is the last node
Topological Sort
- The order of a DAG in such that for every directed edge
(u, v)
, nodeu
comes before nodev
in the ordering - Algorithm:
- Find a vertex with no incoming edge and put it in the final order
- Usually the one with lowest priority is chosen
- Delete all its out going edge
- Repeat 1 & 2
- Find a vertex with no incoming edge and put it in the final order
- There are many possible outcomes for a topological sort
- Topological sorting can be used to find a valid sequence of tasks that must be completed in order to satisfy dependencies between them.
Lecture 19: Shortest Path Algorithms
Dijkstra’s Algorithm:
- Used for finding shortest path in weighted directed and undirected graphs with non-negative weighted edges
- Algorithm:
- An boolean array of unvisited nodes {F, T, …, T}
- An array of cost for each vertex {0, inf,…, inf}
- While unvisited vertices have T
- Take the smallest cost vertex, update visited vertices set
- examine each of its unvisited vertices
- Calculate distance of each neighbor vertex from stat
- if new distance less than in the cost, update it
Spanning trees
- A subset of a connected graph that covers all vertices with minimum number of edges, number of vertices -1 ,
- There are more than 1 possible spanning tree, max
- Has no cycle
Minimum spanning trees (SMT)
- A subset of a weighted graph with smallest weight combines from all edges
- If all edges have distinct weight, there is only 1 possible MST
Prim’s Algorithm
- Greedy algorithm that finds the MST of a graph
- Algorithm:
- Create a boolean array to keep track of visited nodes and initialize all nodes as unvisited.
- Create an array to store the parent node for each node in the minimum spanning tree.
- Create an array to store the key (minimum weight) of each node and initialize all keys as positive infinity.
- Choose any node as the starting node (let’s say node 0). Mark it as visited and set its key to 0.
- Repeat the following steps until all nodes are visited: a. From the set of unvisited nodes, choose the node with the minimum key value. b. Mark the chosen node as visited. c. Update the keys of adjacent unvisited nodes if their weight is smaller than the current key. d. Set the parent of each updated node as the chosen node.
- Build the minimum spanning tree using the parent array.
- Calculate the total cost of the minimum spanning tree.
Kruskal’s Algorithm O(E.logn)
- Greedy algorithm that finds the MST of a graph
- The algorithm starts by sorting the edges of the graph by weight. The algorithm then adds the edges with the smallest weight until all vertices are connected
- Algorithm:
- Sort all the edges in non-decreasing order of the weights
- Pick the smallest edge that doesnt form a cycle with the MST, include to MST, else remove
- Repeat until there are n - 1 edges in mst
Lecture 21: Introduction to Hashing
Hash table
- Efficient data structure that allows direct access by any index type
- Like ,lookup table, dictionary with (key, value) pair
- Key: index into hash table
- Value: information being looked up
- Like ,lookup table, dictionary with (key, value) pair
- Hashing algorithm: have many hashing functions
Hash Functions
- Takes an input (or “key”) and returns a fixed-size output (or “hash value”) called bucket array
Collision:
-
More than 1 key to map into a single index
-
Choose better has function that distributes entries uniformly though out the hash table
-
Solution:
- Open hashing (separate chaining):
- Keys with same hash code are linked by linked list from the first cell
- Easy, wont overload, commonly used when not known the nb of keys and their frequency
- Required linked list, can be unbalanced and need to search for item in linked list
- Keys with same hash code are linked by linked list from the first cell
-
Close hashing (open addressing):
-
All keys are stored in the hash table in empty slot
-
Size of the table must be greater than or equal to nb of keys
- Linear Probing: if is occupied, assign to the next free index
- Quadratic Probing: if , every fail
- Double Hashing:
- Double hash , every fail
- is table size and prime must be smaller than table size
-
- Open hashing (separate chaining):
Lecture 22: Hashing and Maps in Java
HashSet: (implements Set interface)
- Every element added is hashed so there is no particular order
- Doesn’t have any particular order
- HashSet uses HashMap for storing its object
-
- Measures how full of the hashset tis allowed to get before its capacity is automatically increased
Map
- Associative array: ordered pairs (by key) whose entries are known as key and value
- An object that maps keys to values
- Key must be unique, values can be duplicate
- HashMap: ordered of entries is based on hash codes
- LinkedHashMap: Preserves the insertion order
- TreeMap: sorted by the keys or comparator
- Generic map in Java:
- Entries in the map are indexed by keys
- Methods:
- size(): return number of entries in M
- isEmpty():
- get(k): return the value v of k, otherwise null
- put(k,v): add entry if k is new, otherwise replace value v
- remove(k)
- keySet(): returns iterable collection contains all keys
- values(): returns iterable collection contains all values (might contains repeated value)
- entrySet(): return iterable collection contain all key-value
Bloom filtering:
- A space-efficient probabilistic data structure that tells whether an item maybe in the set or not in the set
- Uses many hash functions and set the element in the bucket to true
- The output might be false positive (it is not there but output said there might be) but never false negative (any element is 0 means it is not in the set)
Cuckoo hashing:
- Cuckoo hashing: a form of open addressing in which each non-empty cell of a hash table contains a key or key–value pair.
- Requires 2 hash functions and 2 hash table
- Hash1 the element and insert until there is conflict, replace in hash1 table and hash2 the original conflicting element, put in hash2 table. If there is conflict in hash2 table, replace it in hash2 table and hash1 the original conflicting element.
- wIf there is infinite loop, replace hashing function
Breath first search BFS
- Keep a queue to keep track of nodes to visit
- If there is node from child, add
Depth first search DFS
- Keep visiting children until there is none left