Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

Introduction to

Data Structures & Algorithms

Dr Vi Chi Thanh – thanhvc17@fe.edu.vn


https://vichithanh.github.io
Topics

1. Overview, DSA, OOP and Java 6. Tree


2. List 7. Graph
3. Stack 8. Sorting
4. Queue 9. Hashing
5. Recursion 10.Text Processing

THURSDAY, 07 SEPTEMBER 2023 2


What are they?

• What is a data structure?


• What is an algorithm?
• Not yet to answer but let’s see some examples

THURSDAY, SEPTEMBER 7, 2023 DATA STRUCTURES AND ALGORITHMS - IT511 3


Examples

• You have a book-shelf.


• How to arrange books into the book-shelf?
• Why ?
• To travel to all famous tourist sites in HCM city.
• What route and schedule should you follow?
• Why should you do like that?

THURSDAY, 07 SEPTEMBER 2023 DATA STRUCTURES AND ALGORITHMS - IT511 4


What are they?

• A data structure is
• an arrangement of data
• in a computer’s memory (or sometimes on a disk).

THURSDAY, 07 SEPTEMBER 2023 DATA STRUCTURES AND ALGORITHMS - IT511 5


What is data structure?
• In computer science, simply speaking a data structure is a way of storing data in a computer
so that it can be used efficiently.
• A data structure is a way of organizing data that considers not only the items stored, but also
their relationship to each other. Advance knowledge about the relationship between data items
allows designing of efficient algorithms for the manipulation of data.
• Often a carefully chosen data structure will allow a more efficient algorithm to be used. The
choice of the data structure often begins from the choice of an abstract data structure. A well-
designed data structure allows a variety of critical operations to be performed on using as little
resources, both execution time and memory space, as possible.
• Different kinds of data structures are suited to different kinds of applications, and some are
highly specialized to certain tasks. For example, B-trees are particularly well-suited for
implementation of databases, while compiler implementations usually use hash tables to look
up identifiers.

THURSDAY, 07 SEPTEMBER 2023 6


Why data structure is important in computer
science?
• Data structures are used in almost every program or software system.
• Data structures provide a means to manage huge amounts of data efficiently,
such as large databases and internet indexing services.
• Usually, efficient data structures are a key to designing efficient algorithms.
Some formal design methods and programming languages emphasize data
structures, rather than algorithms, as the key organizing factor in software
design.
• Niklaus Emil Wirth (born February 15, 1934) is a Swiss computer scientist said:
Algorithms + Data Structures = Programs

THURSDAY, 07 SEPTEMBER 2023 7


Basic types of data structure

• In programming, the term data structure refers to a scheme for


organizing related pieces of information. The basic types of data
structures include:
• files, lists, arrays
• records, trees, tables
• Each of these basic structures has many variations and allows
different operations to be performed on the data.

THURSDAY, 07 SEPTEMBER 2023 8


What are they? Algorithms

• Are sequences of instructions


• To manipulate the data in these data structures
• In a variety of ways.
• Such as
• Insert a new data item
• Delete a specified item
• Iterate through all the items in a data structure
• Sorting in-order all items in a data structure

THURSDAY, 07 SEPTEMBER 2023 DATA STRUCTURES AND ALGORITHMS - IT511 9


What is algorithm?

• A formula or set of steps for solving a particular problem. To be an algorithm,


a set of rules must be unambiguous and have a clear stopping point.
Algorithms can be expressed in any language, from natural languages like
English or French to programming languages like FORTRAN.
• We use algorithms every day. For example, a recipe for baking a cake is an
algorithm.
• Most programs, with the exception of some artificial intelligence applications,
consist of algorithms.
• Inventing elegant algorithms -- algorithms that are simple and require the fewest
steps possible -- is one of the principal challenges in programming.

THURSDAY, 07 SEPTEMBER 2023 10


Algorithm example

THURSDAY, 07 SEPTEMBER 2023 11


What are the properties of an algorithm?

• Input - an algorithm accepts zero or more inputs


• Output - it produces at least one output.
• Finiteness - an algorithm terminates after a finite numbers of steps.
• Definiteness - each step in an algorithm is unambiguous. This means that
the action specified by the step cannot be interpreted (explain the
meaning of) in multiple ways & can be performed without any confusion.
• Effectiveness - it consists of basic instructions that are realizable. This
means that the instructions can be performed by using the given inputs in
a finite amount of time.
• Generality - it must work for a general set of inputs.
THURSDAY, 07 SEPTEMBER 2023 12
How to represent algorithms?
• Use natural languages
• too verbose
• too "context-sensitive"- relies on experience of reader
• Use formal programming languages
• too low level
• requires us to deal with complicated syntax of programming language
• Pseudo-Code (alias programming language) - natural language constructs modeled to
look like statements available in many programming languages.
• Flowchart (diagram) - A flowchart is a common type of chart, that represents an
algorithm or process, showing the steps as boxes of various kinds, and their order by
connecting these with arrows. Flowcharts are used in analysing, designing,
documenting or managing a process or program in various fields.

THURSDAY, 07 SEPTEMBER 2023 13


Algorithm representation examples

• Problem: find the greatest of three numbers

Flowchart:

begin x := a
Natural language:
Pseudo-code:
find max(a,b,c) function max(a,b,c) True
• Assign x = a Input: a, b, c b>x x := b
• If b great than x then assign Output: max(a,b,c)
x=b x = a; False
• If c great than x then assign c>x
if b > x then x = b;
x=c; if c > x then x = c; False True
• Result: x => max(a,b,c) return x;
end x := c

THURSDAY, 07 SEPTEMBER 2023 14


Data Structures and Algorithms

• Most algorithms operate on data collections


• Collection Abstract Data Type (ADT)
• Methods
• Constructor / Destructor
• Add / Edit / Delete
• Find
• Sort
• ….

THURSDAY, 07 SEPTEMBER 2023 15


Who are you? And why?

• Familiar with OOP in Java/.NET


• Basic programming skill in Java/.NET
• Why you learn this course?
• DSA is one of the most fundamental course in CS and IT.
• Provide necessary knowledge to learn further: Database, Operating
System,….
Program = Data Structure + Algorithms

THURSDAY, 07 SEPTEMBER 2023 16


Objectives

• Understand general concepts of analysing algorithms.


• Can use basic data structures to solve practical problems.
• Know to decide which data structures and/or algorithms should be
used in practical problems.
• Implement all of them in Object Oriented Programming (OOP)

THURSDAY, 07 SEPTEMBER 2023 17


Procedural vs. OO programming

• OOP was invented because procedural languages, such as C, Pascal,


and early versions of BASIC, were found to be inadequate for large
and complex programs.

THURSDAY, 07 SEPTEMBER 2023 18


Procedural vs. OO programming

THURSDAY, 07 SEPTEMBER 2023 19


Procedural vs. OO programming

• Two problems of Procedural programming:


• Prob 1: Poor Modeling of the Real World
• A thermostat control program (furnaceON, furnaceOFF, currentTemp,
desiredTemp)
• How about hundreds of thermostats
• Prob 2: Crude Organizational Units
• Inflexibility of accessing data: there was no way (at least not a flexible way) to
specify that some methods could access a variable and others couldn’t

THURSDAY, 07 SEPTEMBER 2023 20


Object Class vs. Object
Object Class Object

• Template, specification, • Have is own state (set of objects


blueprint for creating objects attributes)
• Don’t have states • Operations

THURSDAY, 07 SEPTEMBER 2023 21


Basic of OOP/ Java Programming
Class Object
class thermostat • Specifying a class doesn’t create
{ any objects of that class
private float currentTemp(); • To create Object: use the keyword
private float desiredTemp(); new
public void furnace_on() thermostat therm1, therm2; // create
{ // method body goes here } two references
public void furnace_off() therm1 = new thermostat(); // create
two objects and
{ // method body goes here }
therm2 = new thermostat(); // store
} // end class thermostat references to them

THURSDAY, 07 SEPTEMBER 2023 22


Accessing Object Methods

• Use the dot operator (.)


• Example:
therm1.furnace_on();
therm2.furnace_on();

THURSDAY, 07 SEPTEMBER 2023 23


Constructors

• A special method that’s called automatically whenever a new object


is created
• Allows a new object to be initialized in a convenient way
• Always has exactly the same name as the class
• Example: BankApp.java

THURSDAY, 07 SEPTEMBER 2023 24


class BankAccount class BankApp

{ {

private double balance; // account balance public static void main(String[] args)
{
// constructor
BankAccount ba1 = new BankAccount(100.00); //
public BankAccount(double openingBalance)
create acct
{ balance = openingBalance; }

// makes deposit System.out.print("Before transactions, ");


public void deposit(double amount) ba1.display(); // display balance
{ balance = balance + amount; }

// makes withdrawal ba1.deposit(74.35); // make deposit

public void withdraw(double amount) ba1.withdraw(20.00); // make withdrawal

{ balance = balance - amount; }

// displays balance System.out.print("After transactions, ");


ba1.display(); // display balance
public void display()
} // end main()
{ System.out.println("balance=" + balance); }
} // end class BankApp
} // end class BankAccount

THURSDAY, 07 SEPTEMBER 2023 25


JAVA - Access modifiers and access level

Modifier Class Package Subclass World

public Y Y Y Y

protected Y Y Y N

no modifier Y Y N N

private Y N N N
THURSDAY, 07 SEPTEMBER 2023 26
Feature of OOP

• Inheritance
• Extend existing class
• Data Encapsulation
• Hide data access from outside
• Data Abstraction
• Hide implementation from outside
• Polymorphism (Overriding)

THURSDAY, 07 SEPTEMBER 2023 27


Practice

• Download and install Java JDK:


https://www.oracle.com/java/technologies/downloads/
• To compile a Java code (i.e., HelloWorld.java)
javac HelloWorld.java
➔ will produce “HelloWorld.class” file
• To run the compiled Java code
java HelloWorld

• Install and run the file from NetBeans


• Example codes: https://tinyurl.com/ydk73prs
THURSDAY, 07 SEPTEMBER 2023 28
Exercise 1

• Compile and run “Hello.java” (first program)


• Print "This is my first Java program" on the next line by adding
another print statement,
• or (2) by including the message in the same print statement (escape
sequence).

THURSDAY, 07 SEPTEMBER 2023 DATA STRUCTURES AND ALGORITHMS - IT511 29


Exercise 2

• Compile and run “PlusOperator.java” (numbers and strings, output)


• Remove the parentheses enclosing the arithmetic addition and
explain what happens and why.
• Try other parenthesizing and explain the results.
• Print strings and arithmetic expressions with different statements.
• Modify the program to compute the celsius equivalent of today's
temperature (use the formula C=(F-32)*5/9).

THURSDAY, 07 SEPTEMBER 2023 DATA STRUCTURES AND ALGORITHMS - IT511 30


Exercise 3

• Compile and run “Arithmetic.java”


• Note the difference between integer division and floating-point
division, explain the modulo operation.

THURSDAY, 07 SEPTEMBER 2023 DATA STRUCTURES AND ALGORITHMS - IT511 31


Exercise 4

• Compile and run “PrimitiveTypes.java” (primitive data types)


• Explain the output
• Print the values of the variables (combine them in the string)
• Fix the overflow problem (two's complement representation) with long, float, and double
types and explain the difference
• Try 2.147483647E9 instead of 2147483647 and explain what happens and why (narrowing
conversion)
• Explain the Boolean expressions, why (a > b) == !(a < b) is false, and how to fix it (make a not
equal to b, or change expression)
• Write a program from scratch to compute the Celsius equivalent of today's
temperature (use the formula C=(F-32)*5/9). Use BlueJ to create a new project
and a new class, then add the code for the main method.

THURSDAY, 07 SEPTEMBER 2023 DATA STRUCTURES AND ALGORITHMS - IT511 32


Exercise 5

• Compile and run ”BankApp.java” (classes, "uses" relation)


• Move the BankAccount class into a separate file.
• For each transaction print its type and the balance after the
transaction
• Add a method to class BankAccount that returns the balance. Use it
to print the current balance instead of using display().
• Create a second bank account and move the entire balance of the
first account to the second one

THURSDAY, 07 SEPTEMBER 2023 DATA STRUCTURES AND ALGORITHMS - IT511 33


Exercise 6

• Compile and run “GasMileage.java” (input, the use of Scanner class


to read numeric data)
• What happens if you enter 20.5 for miles? Fix the problem in two
ways.
• What happens if enter miles and gallons on the same line?
• Modify the program so that it reads two lines of inputs of two cars,
miles, and gallons (separated by blanks) and prints mpg for each car.

THURSDAY, 07 SEPTEMBER 2023 DATA STRUCTURES AND ALGORITHMS - IT511 34


Exercise 7

• Have a look at and understand “Student.java”, ”Students.java”,


”students.txt” (text files, loops, decision making, access modifiers)
• Add public/private to the declaration of student names and print students
with System.out.println(st.lname), explain.
• Change the while-loop with a for-loop
• Use grade to determine the type of the student: excellent (> 89), ok
[60,89], and failure (< 60)
• Do counting and averaging within each student type (excellent, ok, and
failure)

THURSDAY, 07 SEPTEMBER 2023 DATA STRUCTURES AND ALGORITHMS - IT511 35


THANK YOU

Dr Vi Chi Thanh – thanhvc17@fe.edu.vn


https://vichithanh.github.io

You might also like