Professional Documents
Culture Documents
Coventry University, UK
05.09.2015
Learning Outcomes
Object Oriented
Programming
Concepts
Algorithms
and their
Complexity
Recursion
Sorting
Algorithms
Linked Lists,
Trees and Graphs
05.09.2015
Object Oriented
Programming Concepts
Many languages support a method called object oriented
programming.
This method allows you to break a program up into objects.
Objects are pieces of code that consist of both functions and data.
Multiple functions and data items can be combined into an object.
Objects can also be reused.
Objects will often represent real objects that the program is
trying to represent e.g. employee, or student.
05.09.2015
Object Oriented
Programming Concepts
When you define an object you are really defining a class of objects.
A class acts like a template for an object.
A class on its own does nothing.
But once you have defined a class you can create many
instances of it.
These are called objects.
Objects are what do things and store data.
05.09.2015
Object Oriented
Programming Concepts
Main concepts
Encapsulation
Inheritance
Polymorphism
Abstraction
05.09.2015
Object Oriented
Programming Concepts
Inheritance
A class can use the member variables and methods of another class.
This is achieved through a mechanism called inheritance.
Inheritance can be thought of as specialising a general case into
a more specific case.
For example, a car, or a bike, is a specialisation of a vehicle, which
is more general class.
05.09.2015
Object Oriented
Programming Concepts
public class Bicycle
{
public int gear;
public int speed;
public Bicycle(int startSpeed, int startGear)
{
gear = startGear;
speed = startSpeed;
}
05.09.2015
Object Oriented
Programming Concepts
public void setGear(int newValue)
{
gear = newValue;
}
public void applyBrake(int decrement)
{
speed -= decrement;
}
public void speedUp(int increment)
{
speed += increment;
} }
05.09.2015
Object Oriented
Programming Concepts
public class MountainBike extends Bicycle {
public int seatHeight;
public MountainBike(int startHeight,
int startSpeed,
int startGear) {
super(startSpeed, startGear);
seatHeight = startHeight;
}
public void setHeight(int newValue)
{
seatHeight = newValue;
}
}
05.09.2015
Object Oriented
Programming Concepts
Abstract class
A class which contains the abstract keyword in its declaration is
known as abstract class.
Abstract classes may or may not contain abstract methods ie.,
methods with out body ( public void get(); )
But, if a class have at least one abstract method, then the
class must be declared abstract.
If a class is declared abstract it cannot be instantiated.
To use an abstract class you have to inherit it from another class,
provide implementations to the abstract methods in it.
If you inherit an abstract class you have to provide implementations
to all the abstract methods in it.
05.09.2015
Object Oriented
Programming Concepts
Abstract class
abstract class GraphicObject
{
int x, y;
void moveTo(int newX, int newY) { ... }
abstract void draw();
abstract void resize();
}
05.09.2015
10
Object Oriented
Programming Concepts
Abstract class
class Circle extends GraphicObject
{
void draw() { ... }
void resize() { ... }
}
11
Object Oriented
Programming Concepts
Encapsulation
Encapsulation in Java is a mechanism of wrapping the data (variables)
and code acting on the data (methods) together as a single unit.
In encapsulation the variables of a class will be hidden from other
classes, and can be accessed only through the methods of their
current class, therefore it is also known as data hiding.
To achieve encapsulation in Java
1. Declare the variables of a class as private.
2. Provide public setter and getter methods to modify and view the
variables values.
05.09.2015
12
Object Oriented
Programming Concepts
public class EncapTest
{
private String name;
private int age;
public int getAge() { return age; }
public String getName() { return name; }
13
Object Oriented
Programming Concepts
The public setX() and getX() methods are the access points of the
instance variables of the EncapTest class.
Normally, these methods are referred as getters and setters.
Therefore any class that wants to access the variables should access
them through these getters and setters.
05.09.2015
14
Object Oriented
Programming Concepts
Polymorphism
Polymorphism is when several classes have the same interface,
often inherited from a base class. E.g. all shapes would have an
area method, though the implementation is different for each shape.
Polymorphism is the ability of an object to take on many forms.
The most common use of polymorphism in OOP occurs when a parent
class reference is used to refer to a child class object.
Any Java object that can pass more than one IS-A test is considered
to be polymorphic.
05.09.2015
15
Object Oriented
Programming Concepts
16
05.09.2015
17
05.09.2015
18
05.09.2015
19
20
05.09.2015
21
22
https://www.youtube.com/watch?v=6hfOvs8pY1k
05.09.2015
23
05.09.2015
24
05.09.2015
25
05.09.2015
26
05.09.2015
27
28
05.09.2015
29
05.09.2015
30
05.09.2015
(n times)
(n times)
(n times)
(n*n times)
(n*n times)
(n*n times)
(n times)
31
05.09.2015
32
33
05.09.2015
34
Activity 1
Write the functions below in order of asymptotic growth rate,
beginning with the largest. If any of the functions have the same
growth rate, be sure to show it.
42
4
+
1.5
3log()
40
log()
05.09.2015
35
Activity 1 Solution
05.09.2015
36
Activity 2
Examine the graph below. The plots A, B, C, D, E represent the growth
rates log(), 2 , 4 , 20, 3. State the function for each plot.
05.09.2015
37
Activity 2 Solution
A 2
B 3
C 20
D log()
E 4
05.09.2015
38
Recursion
What is recursion?
A recursive function calls itself.
It must have a condition to stop this process.
This is the base case.
Example: 0 = 1 is always true.
Every other case should take us toward the base case.
This is the recursive case
Example: = 1 for all x>1
05.09.2015
39
Recursion
Example
Factorial:
5! = 5 = 5 4 3 2 1
FACTORIAL(n)
if(n < 2)
return 1
else
return FACTORIAL(n-1) * n
The recursion stops when n is 1.
05.09.2015
40
Recursion
Example
05.09.2015
41
Recursion
Another example
Binary search:
http://www.cs.armstrong.edu/liang/animation/web/BinarySearch.html
BINARY_SEARCH(A, v, first, last)
if last < first
return false
i first + (last - first)/2
if A[i] == v
return true
if A[i] > v
BINARY_SEARCH(A,v,first,i-1)
else
BINARY_SEARCH(A,v,i+1,last)
05.09.2015
//Base case 1
//Base case 2
//Recursion case 1
//Recursion case 2
42
Recursion
Another example
Towers of Hanoi:
http://www.dynamicdrive.com/dynamicindex12/towerhanoi.htm
05.09.2015
43
Sorting Algorithms
Introduction
Sorting data is a fundamental problem in software development
and also a core topic in computer science.
If we consider that the "information age" is all about data,
and we have huge amounts of it then dealing with the data
efficiently is critical.
Today, we will be looking at a selection of sorting algorithms.
05.09.2015
44
Sorting Algorithms
Bogosort
05.09.2015
45
Sorting Algorithms
Bogosort
05.09.2015
46
Sorting Algorithms
Insertion sort
Pick the first item.
Keep swapping it with its left neighbour until the swap would put
it to the left of a number smaller than it.
Pick the next number along.
Repeat.
05.09.2015
47
Sorting Algorithms
Insertion sort
05.09.2015
48
Sorting Algorithms
Insertion sort
INSERTION-SORT(A)
for i 1 to length[A]
key A[i]
ji
while j > 0 and A[j-1] > key
A[j] A[j-1]
jj-1
A[j] key
Best case performance: O()
Worst case performance: O(2 )
Average case performance: O(2 )
05.09.2015
49
Sorting Algorithms
Bubble sort
Examine each consecutive pair of items.
If they are out of order, swap them.
Repeat until no swaps are made.
05.09.2015
50
Sorting Algorithms
Bubble sort
05.09.2015
51
Sorting Algorithms
Bubble sort
BUBBLE(A)
swapTrue
while swap is True:
swapFalse
for i 0 to length(A)-1
if A[i] > A[i+1]
swapTrue
swap(A[i],A[i+1])
Best case performance: O()
Worst case performance: O(2 )
Average case performance: O(2 )
05.09.2015
52
Sorting Algorithms
Merge sort
Divide the unsorted list into n sublists, each containing 1 element
(a list of 1 element is considered sorted).
Repeatedly merge sublists to produce new sorted sublists until
there is only 1 sublist remaining.
This final list will be the sorted list.
05.09.2015
53
Sorting Algorithms
Merge sort
05.09.2015
54
Sorting Algorithms
Merge sort
MERGE-SORT(l):
if length(l) <= 1
return l
al[0 .. length(l)/2]
bl[length(l)/2 .. length(l)]
aMERGE-SORT(a)
bMERGE-SORT(b)
return MERGE(a,b)
05.09.2015
55
Sorting Algorithms
Merge sort
MERGE(a,b)
out array of length length(a)+length(b)
i0
j0
for x 0 length(out)
if a[i] < b[j]
out[x] = a[i]
i++
else
out[x] = b[j]
j++
05.09.2015
56
Sorting Algorithms
Merge sort
57
Sorting Algorithms
Merge sort
05.09.2015
58
Sorting Algorithms
Quick sort
Pick a "pivot.
Create two empty lists, one for all items less than the pivot, one
for all greater.
For each item in the original list, move it to the correct new list.
Now sort each half (by applying this all over again).
05.09.2015
59
Sorting Algorithms
Quick sort
05.09.2015
60
Sorting Algorithms
Quick sort
function QUICKSORT(A)
if length(A)<=1
return A
pivot A[?]
L []
G []
for each x in array
if x pivot
append x to L
else
append x to G
return concatenate(quicksort(L), A[pivot],quicksort(G))
05.09.2015
61
Sorting Algorithms
Quick sort
Best option: pick the value int he middle of the range.
But how? If we have to hunt through to be sure, it can slow things
down a lot.
So pick the first or last item? If the data isn't sorted, it doesn't
matter, so this would be fine.
Except: what if it is sorted? If it's sorted, then we end up
with O(n2) performance.
Take the one in the middle? Better, but could be given data made
specifically to slow it down.
Better: take a random sample, making it nondeterministic.
Better still: take the median of three random items.
05.09.2015
62
Sorting Algorithms
Conclusions
Best case performance: O() or O()
Worst case performance: O(2 )
Average case performance: O()
Often we need the best "average case.
But sometimes we want a guarantee that we never have an awful
worst case.
We might even know we can rely on getting close to best case
situations and pick an algorithm based on that.
Know thy complexities http://bigocheatsheet.com/
05.09.2015
63
Sorting Algorithms
Comparison
05.09.2015
64
Sorting Algorithms
Comparison
05.09.2015
65
Sorting Algorithms
Quick sort
05.09.2015
66
Sorting Algorithms
Bubble sort
05.09.2015
67
Sorting Algorithms
Merge sort
05.09.2015
68
Sorting Algorithms
Insertion sort
05.09.2015
69
Activity 3
Examine the pseudocode below and describe the effect it has on the
given input sequence.
REARRANGE(A)
n <- length(A)
for j <- 0 to n
for i <- 0 to n-1
if (A[i] < A[i+1])
swap (A[i], A[i+1])
05.09.2015
70
Activity 3 Solution
05.09.2015
71
Activity 4
Use pseudocode to describe an algorithm that finds the smallest
number in a sequence.
Write a function in the programming language of your choice that
takes two sequences of numbers as parameters and returns a
sequence that contains the non-unique numbers from each input.
That is, those that are in the first and the second lists. There should
be no duplicates in the output. For example, given the sequences [1,
2, 3, 4, 5] and [4, 5, 6, 7], the answer is [4, 5].
05.09.2015
72
Activity 4 Solution
FIND SMALLEST(seq)
if size(seq)<1
raise error
smallest <- seq[0]
for all numbers i in seq
if i<smallest
smallest <- I
return smallest
05.09.2015
73
Activity 4 Solution
def non_unique(a,b):
result = []
for i in a:
if i in b and not i in result:
result.append(i)
return result
05.09.2015
74
05.09.2015
75
05.09.2015
76
05.09.2015
77
78
05.09.2015
79
05.09.2015
80
05.09.2015
81
05.09.2015
82
05.09.2015
83
05.09.2015
84
85
86
05.09.2015
87
05.09.2015
88
05.09.2015
89
90
91
92
93
05.09.2015
94
05.09.2015
95
05.09.2015
96
Activity 4
05.09.2015
97
05.09.2015
98
99
05.09.2015
100
101
102
05.09.2015
103
05.09.2015
104
05.09.2015
105
05.09.2015
106
05.09.2015
107
05.09.2015
108
109
05.09.2015
110
05.09.2015
111
05.09.2015
112
05.09.2015
113
05.09.2015
114
05.09.2015
115
05.09.2015
116
05.09.2015
117
05.09.2015
118
05.09.2015
119
05.09.2015
120
Activity 5
Describe how a breadth first search (BFS) is performed on a graph
and state the order in which the nodes of the graph below will be
visited, beginning with A. Assume that visited nodes will be
remembered and not visited again, and that left-hand edges are
selected first.
05.09.2015
121
Activity 5 Solution
ABCEFGDHIJ
05.09.2015
122
Discussion
05.09.2015
123