Professional Documents
Culture Documents
— Chinese Proverb
Estructuras de Datos
Sesión 1
Preliminaries and Recursion
c 2011
• Preliminares
⊲ Horario de Clases
⊲ Horario de Consulta
⊲ Créditos
⊲ Intensidad Horaria
⊲ Formato de Clase
⊲ Comportamiento en Clase
⊲ Bibliografı́a
⊲ Página Web
⊲ Docente
⊲ Monitor de Curso
⊲ Calendario Académico
⊲ Evaluaciones
⊲ Formato de las Evaluaciones Parciales
⊲ Evaluaciones Supletorias
⊲ Publicación de Calificaciones
⊲ Reclamación de Calificaciones
⊲ Programa—Calendario
• Recursion
⊲ Example 1: Factorial
⊲ Example 2: Fibonacci Numbers
⊲ Example 3: The Pascal Triangle
⊲ Example 4: Reversing a String
⊲ Example 5: Reversing the Tokens of a String
⊲ Recursion is Difficult to Master
⊲ When to Use Recursion
⊲ Problems You Should Try
⊲ Exercises
Preliminares
Horario de Clases
Formato de la Clase :
• La clase comiezá transcurridos diez (10) minutos de la hora estable-
cida para su inicio
– Si llega tarde: esté suficientemente preparado porque ...
Bibliografı́a
La página web del curso contendrá información relevante para los estudi-
antes, de modo que sugerirı́a que la revisara con frecuencia. La dirección
URL es:
http://disi.unal.edu.co/∼ypinzon/2016699/
Docente
Yoan Pinzón
Oficina : 453-116
eMail : ypinzon@unal.edu.co
WWW : http://disi.unal.edu.co/∼ypinzon/
T.B.A.
Calendario Académico
Feb 2011 W
e Mar 2011 W
e Abr 2011 W
e May 2011 W
e Jun 2011 W
e
e e e e e
L M M J V k L M M J V k L M M J V k L M M J V k L M M J V k
31 1 2 3 4 1 2 3 4 4 1 8 2 3 4 5 6 12 1 2 3 16
7 8 9 10 11 1 7 8 9 10 11 5 4 5 6 7 8 9 9 10 11 12 13 13 6 7 8 9 10
14 15 16 17 18 2 14 15 16 17 18 6 11 12 13 14 15 10 16 17 18 19 20 14 13 14 15 16 17
21 22 23 24 25 3 21 22 23 24 25 7 18 19 20 21 22 23 24 25 26 27 15 20 21 22 23 24
28 4 28 29 30 31 8 25 26 27 28 29 11 30 31 16 27 28 29 30
inicio/fin de clases
primera evaluación ordinaria (28Mar2011)
segunda evaluación ordinaria (16May2011)
semana santa
je
ta
nt r
rc r
os
en
Pu alo
Po alo
V
V
N1 Quices (07Feb-25Mar) 50 10%
N2 1ra Evaluación (28Mar) 150 30%
N3 Quices (29Mar-13May) 50 10%
N4 2da Evaluación (16May) 150 30%
N5 Talleres (07Feb-03Jun) 100 20%
Total: 500 100%
Evaluaciones
aaaaa
aaaaa
aaaaa
N2
aaaaa
(150)
a (400pts)
ctica (100pts)
aaaN1(50)
aaaaa
a aaaaaaa N5
a a a aaaaa
aaaaaaaa
(100)
aa aaaaa
Teori
aaaaaN4 a a
aaaaaa
N3
aaaaa(150)
P rá
a
aaaaaaaaaaa a
(50
aaaaaaaaaa a
a a a a aaa
)
Evaluaciones Supletorias
Reclamación de Calificaciones
Programa—Calendario
Example 1: Factorial
n! = n · (n − 1) · (n − 2) · . . . · 3 · 2 · 1
5! = 5 · 4 · 3 · 2 · 1 = 120
Observation:
n! = n · (n − 1)! (recursive step)
1! = 1 (base step)
class Recursion
{
public static int factorial(int n)
{
if(n <= 1) return 1;
else return n * factorial(n-1);
}
return result ;
}
The Fibonacci series begins with 1 and 1 and has the property that
each subsequent Fibonacci number is the sum of previous two Fibonacci
numbers.
Observation:
f ib(n) = f ib(n − 1) + f ib(n − 2) (recursive step)
f ib(0) = 1, f ib(1) = 1 (base step)
How many times do we invoke the method fib when computing fib(5)?
fib(5)
5 3
fib(4) fib(3)
3 2 2 1
fib(1) fib(0)
For instance:
(x + 1)3 = x3 + 3x2 + 3x + 1
(x + 1)6 = x6 + 6x5 + 15x4 + 20x3 + 15x2 + 6x + 1
class Recursion
{
public static long pascal (int n, int k)
{
if (k == 0 || k == n) return 1;
else return pascal(n-1,k-1) + pascal(n-1,k);
}
Observe that recursion should be used with care. This method differs
from the one in the previous page in the order statements in lines 9 and
10 are executed.
Whereas the former prints the string reversed the later prints the string
in its normal order.
$ javac Recursion.java
$ java Recursion How:are:you
you
are
How
These rules are not precise, rather they should be seen as guidelines
Exercises
Find an appropriate name for the following methods:
— Chinese Proverb
Estructuras de Datos
Sesión 2
Java Review
c 2011
• Review of Java
⊲ What is Java
⊲ Common Acronyms
⊲ Program Structure
⊲ The main() method
⊲ Comments
⊲ The Braces
⊲ Identifiers
⊲ Good Programming Practice
⊲ Platform Independent
⊲ Applications Vs Applets
⊲ Data Types
⊲ Primitive Data Types
⊲ Reference Data Types
⊲ Methods
⊲ Argument Passing
⊲ Method Overloading
⊲ Argument Promotion
⊲ Objects & Clases
⊲ Inheritance
⊲ Abstract Methods & Classes
⊲ Multiple Inheritance
⊲ Interfaces
⊲ Polymorphism
The Language Itself: Java as a language looks like C++, but get away
from complexities that make it hard to program in C++. The result is a
smaller, simpler language that still allows you to write useful programs.
The Library: Java comes with a very large and useful library of classes
and interfaces. The Java class library supports a large number of capa-
bilities, too numerous to mention at this point.
The Virtual Machine: The people who created Java were pretty specific
about how a computer should actually run a Java program. They created
a virtual machine specification, which is kind of like the design for a
computer chip. Java basically runs programs by simulating that chip in
software.
Common Acronyms
GUI: Graphical User Interface
AWT: Abstract Windowing Toolkit – This was the GUI used by JDK
1.0 - JDK 1.1
JVM: Java Virtual Machine – Software that allows Java bytecode to run
on a physical machine. A JRE is a JVM. Browsers provide a JVM for
Java Applets to execute.
JDK: Java Development Kit – The software package that allows devel-
opers to develop Java programs.
JAR: Java ARchive – A Jar is just a zip file with a renamed extension.
import class_name;
import package_name.*;
. . .
field-declaration 1;
field-declaration 2;
. . .
method-definition 1;
method-definition 2;
. . .
execution-statement 1;
execution-statement 2;
. . .
}
}
Comments
Java has tree types of comments:
(1) Multiline comments (/* .... */): Inherited from C. All the text
between the delimiters of the comment is ignored by the compiler.
(3) Javadoc comments (/** .... */): This form can be used to
provide information to the javadoc utility, which will extract them and
automatically creates some HTML documentation for the program.
The Braces
The opening brace ({) and the closing brace (}) mark the beginning and
the end of the program body. Any code enclosed by the two braces is
referred to as a block. Any variable, or method, defined in a block only
has scope (i.e. is only available) within that block.
Identifiers
In Java, identifiers are used to name variables, constants, classes, and
methods. Identifiers can not be reserved words as:
Platform Independent
Platform independence means that a program can run on any computer
system. Java programs can run on any system for which a Java virtual
machine has been installed.
C++
Pascal Compiler Binary File
LISP Sparc Sparc
ADA
Compiler JVM
PowerPC PowerPC
Applications Vs Applets
There are two ways to run a Java Executable File:
1) A Java Application: Stand-alone Java program that can be run
just by invoking the java interpreter from the command line. All of our
programs will be applications.
public class TrivialApplication {
public static void main(String[] args) {
System.out.println("Hello, Folks");
}
}
In Java the format and size of primitive data types are not
machine-dependent.
Example:
class Point {
private int x, y;
public Point() { x = y = 0; }
public Point( int dx, int dy )
{
x = dx; y = dy;
}
public void move( int dx, int dy )
{
x += dx;
y += dy;
}
public String toString()
{
return "(" + x + "," + y + ")";
}
}
1 class PointTest {
2 public static void main( String [] args )
3 {
4 Point point1 = new Point();
5 Point point2 = new Point( 10,20 );
6 Point point3 = point1;
7
point1 AB00
FA00 AB00 x y
0 0
point2
FC00 AC10 AC10
x y
point3 10 20
FDE0 AB00
12 point1.move( 5, 5 );
point1 AB00
FA00 AB00 x y
5 5
point2
FC00 AC10 AC10
x y
point3 10 20
FDE0 AB00
• return type
• method name
• list of parameters
• body
body-of-the-method;
. . .
}
Argument Passing
Arguments passed to Java methods are passed by value. That is, a copy
of the arguments is made and passed to the corresponding parameters.
Example1:
public class TestSwap {
swap( a, b );
System.out.println( "a=" + a ); // 4
System.out.println( "b=" + b ); // 5
}
}
swap( a, b );
System.out.println( "a=" + a ); // 4
System.out.println( "b=" + b ); // 5
}
}
Because Java passes all arguments by value, this code does not work
So how do you write a method in Java to swap the values of two primitive
type or two object references?
Example3:
class Wraper {
public Object obj;
}
Example:
int max( int a, int b, int c )
int max( int a, int b)
int max( float a, float b, float c)
int max( float a, float b)
The compiler will ensure that the correct method is called based on the
signature (that is, their parameter list types) passed to max().
Argument Promotion
Example:
System.out.println( Math.sqrt( 4 ) ); // 2
The cast operator (type) is used to enable conversions that would nor-
mally be disallowed.
Example:
b = d; // compile error
b = (byte) d; // compiles ok
Later on we will learn how to cast objects from one class to another
A class in Java consist of fields that store data and methods that are
applied to instances of the class.
date1
public Date() {
day = 1;
month = 1;
year = 1900;
}
Shape
Point
Circle
Cylinder
Point.java
1 public class Point extends Shape {
2
3 private int x;
4 private int y;
5
6 public Point() { }
7
8 public Point( int xValue, int yValue ) { x = xValue; y = yValue; }
9
10 public void setX( int xValue ) { x = xValue; }
11
12 public int getX() { return x; }
13
14 public void setY( int yValue ) { y = yValue; }
15
16 public int getY() { return y; }
17
18 public String getName()
19 {
20 return "Point";
21 }
22
23 public String toString()
24 {
25 return "[" + getX() + ", " + getY() + "]";
26 }
27 }
Cylinder.java
1 public class Cylinder extends Circle {
2 private double height;
3
4 public Cylinder() { }
5
6 public Cylinder( int x, int y, double radius, double heightValue ) {
7 super( x, y, radius ); setHeight( heightValue );
8 }
9
10 public void setHeight( double heightValue ) {
11 height = ( heightValue < 0.0?0.0:heightValue );
12 }
13
14 public double getHeight() { return height; }
15
16 public double getArea() {
17 return 2 * super.getArea() + getCircumference() * getHeight();
18 }
19
20 public double getVolume() {
21 return super.getArea() * getHeight();
22 }
23
24 public String getName() { return "Cylinder"; }
25
26 public String toString() {
27 return super.toString() + "; Height = " + getHeight();
28 }
29 }
$ java AbstractInheritanceTest
Point: [7, 11]
Area=0,00
Volume = 0,00
Multiple Inheritance
In Multiple Inheritance, a class may be derived from more than one
base class. For instance, a StudentEmployee could then be derived from
Student class and Employee class.
Interfaces
The interface is the ultimate abstract class. It consists of public abstract
methods and public static final field, only.
While a class may extend only one other class, it may implement
more than one interface.
Point.java
1 public class Point extends Object implements Shape {
2 private int x, y;
3
4 public Point() {}
5
6 public Point( int xValue, int yValue ) {
7 x = xValue; y = yValue;
8 }
9
$ java InterfaceTest
Point: [7, 11]
Area=0,00
Volume = 0,00
16 arr[i].getVolume() + "\n");
17 }
18
19 public static void main( String args[] ) {
20 Shape [] a = { new Point( 7, 11 ),
21 new Circle( 22, 8, 3.5 ), null,
22 new Cylinder(20, 30, 3.3, 10.75) };
23 printAll( a );
24 System.out.println("Total area="+totalArea( a ));
25 }
26 }
— Chinese Proverb
Estructuras de Datos
Sesión 3
Methods of Representing Data, List Data Structure (Part 1)
c 2011
• Preliminaries
Data Structure: Data object along with the relationships that exist
among the instances and elements, and which are provided by specifying
the operations of interest.
FE300 5 2 4 8 9 ...
element size
FE300 5
firstNode
link
data 5 2 4 8 9
node [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
next 6 7 1 -1 5
element 8 5 4 9 2
firstNode
2
firstNode=2
5 2 4 8 9 -1
A linear list is a data object whose instances are of the form (e0, e1, . . . , en−1)
where n is a finite natural number. The ei items are the elements of the
list and n is the length (size).
AbstractDataType LinearList
{
instances: ordered finite collection of zero or more elements
operations:
isEmpty(): return true if the list is empty. false otherwise
size(): return the number of elements in the list
get(index): return the indexth element of the list
indexOf(x): return the position of the first occurrence of x
in the list, return -1 if x is not in the list
remove(index): remove and return the indexth element, elements
with higher index have their index reduced by 1
add(index, x): insert x as the indexth element, elements with
index ≥ index have their index increased by 1
output(): output the list elements from left to right
}
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
element 5 2 4 8 9
(a) location(i)=i
We will use formula
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
(a) location(i) = i,
element 9 8 4 2 5 thus the ith element of
(b) location(i)=9-i the list (if it exists) is
at position i of the ar-
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] ray.
element 8 9 5 2 4
(c) location(i)= (7+i)%10
package dataStructures;
import java.util.*;
import utilities.*;
// constructors
public ArrayLinearList(int initialCapacity) { ... }
public ArrayLinearList() { ... }
// methods
public boolean isEmpty() { ... }
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
FE30
5 2 4 8 9
element size
FE30 5
Constructors
get, indexOf
/** @return element with specified index
* @throws IndexOutOfBoundsException when
* index is not between 0 and size - 1 */
public Object get(int index)
{
checkIndex(index);
return element[index];
}
/** @return index of first occurrence of theElement,
* return -1 if theElement not in list */
public int indexOf(Object theElement)
{
// search element[] for theElement
for (int i = 0; i < size; i++)
if (element[i].equals(theElement))
return i;
If the list does not have an indexth element, then throw an exception
(IndexOutOfBoundsException). Otherwise, move elements eindex+1, eindex+2,
. . . , en−1 one position to the left and reduce the value of n (size).
/** Remove the element with specified index. All elements with
* higher index have their index reduced by 1.
* @throws IndexOutOfBoundsException when
* index is not between 0 and size - 1
* @return removed element */
public Object remove(int index)
{
checkIndex(index);
element[--size] = null;
return removedElement;
}
Inserting an element
Move elements eindex, eindex+1, . . . , en−1 one position to the right, insert
the new element at position index, and increase the value of n (size).
/** All elements with equal or higher index
* have their index increased by 1.
* @throws IndexOutOfBoundsException when
* index is not between 0 and size */
public void add(int index, Object theElement)
{
if (index < 0 || index > size)
throw new IndexOutOfBoundsException
("index = " + index + " size = " + size);
element[index] = theElement;
size++;
}
return newArray;
}
changeLength1D → utilities.ChangeArrayLength
newInstance, getComponentType → java.lang.Class
arraycopy → java.lang.System
if (size > 0)
s.delete(s.length() - 2, s.length());
s.append("]");
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 100
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 101
C:\2016699\all>javac -d . dataStructures\ArrayLinearList.java
C:\2016699\all>java dataStructures.ArrayLinearList
Initial size is 0
List is empty
List size is 4
The list is [1, 2, 4, 6]
The index of 4 is 2
3 not found
Element at 0 is 1
Element at 3 is 6
2 removed
The list is [1, 4, 6]
6 removed
The list is [1, 4]
List is not empty
List size is 2
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 102
If your strength is small, don’t carry heavy burdens. If your words are worthless, don’t give advice.
— Chinese Proverb
Estructuras de Datos
Sesión 4
List Data Structure (Part 2)
c 2011
• Comparison of Representations
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 104
LinearList Data Structure
Linked Representation
firstNode
link
data 5 2 4 8 9
Singly linked list or chain
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 105
class ChainNode
{
Object element;
ChainNode next;
ChainNode(Object element)
{this.element = element;}
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 106
Class definition for a Chain
public class Chain implements LinearList
{
// data members
protected ChainNode firstNode;
protected int size;
// constructors
public Chain(int initialCapacity) { ... }
public Chain() { ... }
// methods
public boolean isEmpty() { ... }
public int size() { ... }
void checkIndex(int index) { ... }
public Object get(int index) { ... }
public int indexOf(Object theElement) { ... }
public Object remove(int index) { ... }
public void add(int index, Object theElement) { ... }
public String toString() { ... }
public static void main(String [] args) { ... }
}
Note: This representation does not specify the maximum size!
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 107
An instance of this class (Chain L of integers) with size=5 will look like
this:
firstNode
link
data 5 2 4 8 9
L
FEFF
size
5
firstNode
FE30
FF10
next
FF26
FEFF FE45 next
FE30 0
element
next
FF10 2 element
element 9
5
FE45
next FA10
FA10 next
element FF26
4 element
8
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 108
Constructors, isEmpty, size, checkIndex
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 109
get
return currentNode.element;
}
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 110
indexOf
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 111
Outputting a Chain
/** convert to a string */
public String toString()
{
StringBuffer s = new StringBuffer("[");
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 112
Deleting the indexth element
1) If index=0
firstNode
link ...
data 0 1 2 n-1
(a) Before
firstNode
link ...
data 1 2 n-1
(b) After
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 113
2) If index > 0
firstNode
(a) Before
firstNode
(b) After
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 114
/** Remove the element with specified index.
* All elements with higher index have their index reduced by 1.
* @throws IndexOutOfBoundsException when
* index is not between 0 and size - 1
* @return removed element */
public Object remove(int index)
{
checkIndex(index);
Object removedElement;
if (index == 0) // remove first node
{
removedElement = firstNode.element;
firstNode = firstNode.next;
}
else
{ // use q to get to predecessor of desired node
ChainNode q = firstNode;
for (int i = 0; i < index - 1; i++)
q = q.next;
removedElement = q.next.element;
q.next = q.next.next; // remove desired node
}
size--;
return removedElement;
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 115
Inserting an element
Insertion and removal work in a similar way. There are two cases to
consider:
1) If index=0
firstNode
... link
0 1 2 n-1 data
New Node
(a) Before
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 116
firstNode
... link
1 2 3 n-1 data
(b) After
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 117
2) If index >0
firstNode
New Node
(a) Before
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 118
firstNode
(b) After
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 119
if (index == 0)
// insert at front
firstNode = new ChainNode(theElement, firstNode);
else
{ // find predecessor of new element
ChainNode p = firstNode;
for (int i = 0; i < index - 1; i++)
p = p.next;
// insert after p
p.next = new ChainNode(theElement, p.next);
}
size++;
}
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 120
Testing Chain Class
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 121
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 122
C:\2016699\all>javac -d . dataStructures\Chain.java
C:\2016699\all>java dataStructures.Chain
Initial size is 0
The list is empty
List size is 4
The list is [1, 2, 4, 6]
The index of 4 is 2
3 not found
Element at 0 is 1
Element at 3 is 6
2 removed
The list is [1, 4, 6]
6 removed
The list is [1, 4]
The list is not empty
List size is 2
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 123
firstNode
link ...
data e0 e1 e2 e3 en-1
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 124
2) Adding an additional node, called the header node, at the front.
headerNode
link ...
data e0 e1 e2 en-1
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 125
// constructor
public CircularWithHeader() { ... }
// methods
public boolean isEmpty() { ... }
public int size() { ... }
void checkIndex(int index) { ... }
public Object get(int index) { ... }
public int indexOf(Object theElement) { ... }
public Object remove(int index) { ... }
public void add(int index, Object theElement) { ... }
public String toString() { ... }
public static void main(String [] args) { ... }
}
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 126
Constructor, isEmpty, size, checkIndex
public CircularWithHeader()
{
headerNode = new ChainNode();
headerNode.next = headerNode;
}
public boolean isEmpty()
{
return size == 0;
}
public int size()
{
return size;
}
void checkIndex(int index)
{
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException
("index = " + index + " size = " + size);
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 127
get
return currentNode.element;
}
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 128
indexOf
if (currentNode == headerNode)
return -1;
else
return index;
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 129
remove
Object removedElement;
ChainNode q = headerNode;
for (int i = 0; i < index; i++) q = q.next;
removedElement = q.next.element;
q.next = q.next.next;
size--;
return removedElement;
}
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 130
add
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 131
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 132
List=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
List=[0, 1, 7, 8, 9]
0 is element 0
1 is element 1
2 is element -1
3 is element -1
4 is element -1
5 is element -1
6 is element -1
7 is element 2
8 is element 3
9 is element 4
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 133
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 134
The one who turns in his own, shall dig two graves.
— Chinese Proverb
Estructuras de Datos
Sesión 5
Stack Data Structure
c 2011
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 136
Stacks Data Structure
A stack is a linear list in which insertions (also called additions) and
deletions take place at the same end. This end is called the top. The
other end is called the bottom.
top bottom
e e e
1 2 3
... ei ... en- en 1
insertions
deletions
bottom top
e e e
1 2 3
... ei ... en- en 1
insertions
deletions
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 137
operations:
empty(): return true if the stack is empty.
false otherwise.
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 138
Interface Definition of Stack
package dataStructures;
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 139
Observations
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 140
Stack Data Structure
Array-based Representation
• Customised Implementation
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 141
designate the left end of the list as the bottom and the right end as
the top
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 142
Class definition of DerivedArrayStack
public class DerivedArrayStack extends ArrayLinearList implements Stack
{
// constructors
public DerivedArrayStack(int initialCapacity)
{super(initialCapacity);}
public DerivedArrayStack()
{this(10);}
// methods
public boolean empty() {return isEmpty();}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 143
Test program
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 144
Top element is 4
Removed the element 4
Top element is 3
Removed the element 3
Top element is 2
Removed the element 2
Top element is 1
Removed the element 1
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 145
∗ The complexity of push is Θ(1) except when the addition of an element requires us to increase the
capacity of the stack. In this latter case the complexity is O(capacity).
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 146
Implementing Stack as a base class
// constructors
public ArrayStack(int initialCapacity) { ... }
public ArrayStack() { ... }
// methods
public boolean empty() { ... }
public Object peek() { ... }
public void push(Object theElement) { ... }
public Object pop() { ... }
public static void main(String [] args) { ... }
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 147
Constructors
public ArrayStack()
{
this(10);
}
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 148
empty, peek
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 149
push, pop
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 150
Stack Data Structure
Linked Representation
• Customised Implementation
In both cases, we have to decide which end of the chain will be the top
of the stack and which the bottom.
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 151
Using Inheritance
public class DerivedLinkedStack extends Chain implements Stack
{
public DerivedLinkedStack(int initialCapacity)
{super();}
public DerivedLinkedStack()
{this(0);}
public boolean empty() {return isEmpty();}
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 152
Implementing Stack as a base class
// constructors
public LinkedStack(int initialCapacity) { ... }
public LinkedStack() { ... }
// methods
public boolean empty() { ... }
public Object peek() { ... }
public void push(Object theElement) { ... }
public Object pop() { ... }
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 153
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 154
push, pop
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 155
Constructors : Θ(1)
Other operations : Θ(1)
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 156
Stack Application
Parentheses Matching
(((a+b)*c+d*e)/((f+g)-h+i))
(a*(a+b))/(b+d)
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 157
Parentheses Matching
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 158
↓ ↓ ↓
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
( ( ( a + b ) * c + d * e ) / ( ( f + g ) - h ) )
2
1
0
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
( ( ( a + b ) * c + d * e ) / ( ( f + g ) - h ) )
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 159
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 160
public class ParenthesisMatching
{
public static void printMatchedPairs(String expr)
{ ... }
System.out.println("Type an expression");
String expression = keyboard.readString();
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 161
C:\2016699\all>java applications.ParenthesisMatching
Type an expression with no spaces
(((a+b)*c+d*e)/((f+g)-h))
The pairs of matching parentheses in
(((a+b)*c+d*e)/((f+g)-h))
are (indexing begins at 0)
2 6
1 13
16 20
15 23
0 24
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 162
Stack Application
Switchbox Routing
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 163
1 2 3 4 5 6 7 8 9 10
Net={ 1, 2, 3, 4, 4, 3, 2, 5, 5, 1 }
1 2 3
10 4
9 5
8 7 6
Routable!
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 164
1 2 3 4 5 6 7 8 9 10
Net={ 1, 2, 3, 4, 4, 2, 3, 5, 5, 1 }
1 2 3
10 4
9 5
8 7 6
Not Routable!
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 165
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 166
public class SwitchBox
{
public static boolean checkBox(int [] net) { ... }
checkBox(net);
}
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 167
C:\2016699\all>java applications.SwitchBox
Type number of pins
20
Type net numbers for pins 1 through 20
1 2 3 4 4 5 6 6 7 8 9 9 10 10 8 7 5 3 2 1
Switch box is routable
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 168
He who cannot agree with his enemies is controlled by them.
— Chinese Proverb
Estructuras de Datos
Sesión 6
Queue Data Structure
c 2011
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 170
Queue Data Structure
A queue is a special case of linear list where insertions and deletions take
place at different ends
front rear
e e e
1 2 3
... ei ... en- en 1
deletions insertions
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 171
AbstractDataType Queue
{
instances: linear list of elements; one end is called the
the front; the other is the rear;
operations:
isEmpty(): return true if the queue is empty.
false otherwise.
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 172
Interface Definition of Queue
package dataStructures;
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 173
F A T ... A T ...
[0] [1] [2] [0] [1]
front rear
A T E ...
[0] [1] [2]
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 174
◮ Empty queue: rear = -1
◮ Addition:
rear = rear + 1
Θ(1) time
◮ Deletion:
Shift all elements one position to the left.
Θ(n) time
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 175
F A T ... A T ...
[0] [1] [2] [0] [1] [2]
front rear
A T E ...
[0] [1] [2] [3]
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 176
◮ Empty queue: rear < front
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 177
T T T E
A A A
F
front front
front
front points one position before the position of the first element in
the queue.
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 178
◮ Empty queue: front = rear
(initially front=rear=0)
◮ Full queue: (rear+1)%queue.length = front
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 179
Class Definition
// constructors
public ArrayQueue(int initialCapacity) { ... }
public ArrayQueue() { ... }
// methods
public boolean isEmpty() { ... }
public Object getFrontElement() { ... }
public Object getRearElement() { ... }
public void put(Object theElement) { ... }
public Object remove() { ... }
public static void main(String [] args){ ... }
}
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 180
Constructors, isEmpty
public ArrayQueue()
{ // use default capacity of 10
this(10);
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 181
getFrontElement, getRearElement
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 182
remove
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 183
put
public void put(Object theElement)
{
// increase array length if necessary
if ((rear + 1) % queue.length == front)
{// double array size
// allocate a new array
Object [] newQueue = new Object [2 * queue.length];
// copy elements into new array
int start = (front + 1) % queue.length;
if (start < 2)
// no wrap around
System.arraycopy(queue, start, newQueue, 0, queue.length - 1);
else
{ // queue wraps around
System.arraycopy(queue, start, newQueue, 0, queue.length - start);
System.arraycopy(queue, 0, newQueue, queue.length - start, rear + 1);
}
// switch to newQueue and set front and rear
front = newQueue.length - 1;
rear = queue.length - 2;
queue = newQueue;
}
// put theElement at the rear of the queue
rear = (rear + 1) % queue.length;
queue[rear] = theElement;
}
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 184
public static void main(String [] args)
{
ArrayQueue q = new ArrayQueue(3);
q.put(new Integer(1));
q.put(new Integer(2));
q.put(new Integer(3));
q.put(new Integer(4));
while (!q.isEmpty())
{
System.out.println("Rear element is "
+ q.getRearElement());
System.out.println("Front element is "
+ q.getFrontElement());
System.out.println("Removed the element "
+ q.remove());
}
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 185
Rear element is 4
Front element is 1
Rear element is 4
Front element is 2
Rear element is 4
Front element is 3
Rear element is 4
Front element is 4
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 186
Queue Data Structure
Linked Representation
...
front rear
...
front rear
(a) Addition
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 187
...
front rear
(b) Deletion
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 188
Class Definition
// constructors
public LinkedQueue(int initialCapacity) {}
public LinkedQueue() {this(0);}
// methods
public boolean isEmpty() { return front == null; }
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 189
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 190
put
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 191
remove
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 192
Queue Application
Image-Component Labeling
1 2
1 1 2 2
1 3
1 1 3 3
1 1 1 4 3 5
1 1 1 1 4 4 4 5
1 1 1 1 1 4 4 4 5 5
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 194
import dataStructures.*;
import utilities.*;
// data members
private static int [][] pixel;
private static int size;
// methods
private static void inputImage() { ... }
private static void labelComponents() { ... }
private static void outputImage() { ... }
public static void main(String [] args)
{
inputImage();
labelComponents();
outputImage();
}
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 195
// constructor
private Position(int theRow, int theCol)
{
row = theRow;
col = theCol;
}
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 196
private static void inputImage()
{
// define the input stream to be the standard
// input stream
MyInputStream keyboard = new MyInputStream();
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 197
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 198
private static void labelComponents()
{
// initialize offsets
Position [] offset = new Position [4];
offset[0] = new Position(0, 1); // right
offset[1] = new Position(1, 0); // down
offset[2] = new Position(0, -1); // left
offset[3] = new Position(-1, 0); // up
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 199
do
{ // find rest of component
for (int i = 0; i < numOfNbrs; i++)
{ // check all neighbors of here
nbr.row = here.row + offset[i].row;
nbr.col = here.col + offset[i].col;
if (pixel[nbr.row][nbr.col] == 1)
{ // pixel is part of current component
pixel[nbr.row][nbr.col] = id;
q.put(new Position(nbr.row, nbr.col));
}
}
// any unexplored pixels in component?
here = (Position) q.remove();
} while(here != null);
} // end of if, for c, and for r
}
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 200
File ImageComponents.input:
7
0 0 1 0 0 0 0
0 0 1 1 0 0 0
0 0 0 0 1 0 0
0 0 0 1 1 0 0
1 0 0 0 1 0 0
1 1 1 0 0 0 0
1 1 1 0 0 0 0
File ImageComponents.output:
Enter image size
Enter the pixel array in row-major order
The labeled image is
0 0 2 0 0 0 0
0 0 2 2 0 0 0
0 0 0 0 3 0 0
0 0 0 3 3 0 0
4 0 0 0 3 0 0
4 4 4 0 0 0 0
4 4 4 0 0 0 0
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 201
Queue Application
Lee’s Wire Router
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 202
6 6
5 6 2 3 4 5 6 5 6 2 3 4 5 6
4 1 2 4 1 2
3 2 1 S 1 3 2 1 S 1
3 2 1 2 3 3 2 1 2 3
3 T 3 T
6 5 4 5 6 6 5 4 5 6
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 203
import dataStructures.*;
import utilities.*;
// data members
private static int [][] grid;
private static int size;
private static int pathLength;
private static ArrayQueue q;
private static Position start, finish;
private static Position [] path; // the shortest path
// methods
private static void inputData() { ... }
private static boolean findPath() { ... }
private static void outputPath() { ... }
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 204
public static void main(String [] args)
{
inputData();
if ( findPath() ) outputPath();
else System.out.println("There is no wire path");
}
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 205
// constructor
private Position(int theRow, int theCol)
{
row = theRow;
col = theCol;
}
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 206
private static void inputData()
{
MyInputStream keyboard = new MyInputStream();
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 207
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 208
private static boolean findPath()
{
if ((start.row == finish.row) && (start.col == finish.col))
{ // start == finish
pathLength = 0;
return true;
}
// initialize offsets
Position [] offset = new Position [4];
offset[0] = new Position(0, 1); // right
offset[1] = new Position(1, 0); // down
offset[2] = new Position(0, -1); // left
offset[3] = new Position(-1, 0); // up
// initialize wall of blocks around the grid
for (int i = 0; i <= size + 1; i++)
{
grid[0][i] = grid[size + 1][i] = 1;
grid[i][0] = grid[i][size + 1] = 1;
}
Position here = new Position(start.row, start.col);
grid[start.row][start.col] = 2; // block
int numOfNbrs = 4; // neighbors of a grid position
ArrayQueue q = new ArrayQueue();
Position nbr = new Position(0, 0);
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 209
do
{// label neighbors of here
for (int i = 0; i < numOfNbrs; i++)
{// check out neighbors of here
nbr.row = here.row + offset[i].row;
nbr.col = here.col + offset[i].col;
if (grid[nbr.row][nbr.col] == 0)
{ // unlabeled nbr, label it
grid[nbr.row][nbr.col]
= grid[here.row][here.col] + 1;
if ((nbr.row == finish.row) &&
(nbr.col == finish.col)) break; // done
// put on queue for later expansion
q.put(new Position(nbr.row, nbr.col));
}
}
// have we reached finish?
if ((nbr.row == finish.row) &&
(nbr.col == finish.col)) break; // done
if (q.isEmpty()) return false; // no path
here = (Position) q.remove(); // get next position
} while(true);
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 210
// construct path
pathLength = grid[finish.row][finish.col] - 2;
path = new Position [pathLength];
return true;
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 211
File WireRouter.input:
7
3 2
4 6
0 0 1 0 0 0 0
0 0 1 1 0 0 0
0 0 0 0 1 0 0
0 0 0 1 1 0 0
1 0 0 0 1 0 0
1 1 1 0 0 0 0
1 1 1 0 0 0 0
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 212
File WireRouter.output:
Enter grid size
Enter the start position
Enter the finish position
Enter the wiring grid in row-major order
The wire path is
4 2
5 2
5 3
5 4
6 4
6 5
6 6
5 6
4 6
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 213
A wise man makes his own decisions, an ignorant man follows the public opinion.
— Chinese Proverb
Estructuras de Datos
Sesión 7
Analysis of Algorithms & Sorting
c 2011
• Analysis of Algorithms
⊲ Growth of Functions
⊲ Growth Rates
⊲ Asymptotic Notation: O, Ω, Θ
• Sorting Algorithms
⊲ Selection Sort
⊲ Bubble Sort
⊲ Insertion Sort
⊲ Merge Sort
⊲ Quick Sort
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 215
Growth of Functions
– How does the running time of an algorithm increase with the size
of the input in the limit as the input increases in size without
bound?
– Define sets of functions that satisfy certain criteria and use these
to characterize time and space complexity of algorithms
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 216
time
2n-7
n
0.5n+3
n
(a) Growth of Functions (Linear)
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 217
time
2n
n2
n
log n
n
(b) Growth Rates
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 218
Growth Rates
0, f (n) grows slower than g(n)
f (n)
← ∞, f (n) grows faster than g(n)
lim
n→∞ g(n)
otherwise f (n) and g(n)
have the same growth rate
f (n) ≺ g(n)
lim f (n)/g(n) = 0
n→∞
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 219
Asymptotic Notations
• Deal with the behavior of functions in the limit (for sufficiently large
value of its parameters)
– 7n − 3 is O(n)
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 220
f(n)
n0 n
f(n)=O(g(n))
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 221
The Ω Notation
f (n) = Ω(g(n)) if there exist positive constants c and n0 such that for
every n ≥ n0,
f (n) ≥ cg(n)
time
f(n)
cg(n)
n0 n
f(n)= (g(n))
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 222
The Θ Notation
f (n) = Θ(g(n)) if f (n) = O(g(n)) and f (n) = Ω(n), or equivalently, if
there are positive constants c1, c2 and n0 such that for every n ≥ n0,
c1g(n) ≤ f (n) ≤ c2g(n)
time
c2 g(n)
f(n)
c1 g(n)
n0 n
f(n)=£(g(n))
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 223
Danger of Asymptotic Notation
• Even though the former algorithm is better for all but finitely many
instances, the latter is better for all the instances that can exist in
the known universe.
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 224
• constant O(1)
• logarithmic O(log n)
• polylogarithmic O(logc n), c ≥ 1
• n log n O(n log n)
• sublinear O(na), 0 < a < 1
• linear O(n)
• quadratic O(n2)
• polynomial O(nc), c ≥ 1
• exponential O(cn), c > 1
• factorial O(n!)
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 225
Sorting Algorithms
• Sorting is a fundamental application for computers
Examples
• Words in a dictionary
• Files in a directory
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 226
Preliminaries
• Java provides a comparison method that is imparted to a class by
implementing the java.lang.Comparable interface.
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 227
Implementing a Comparable Interface
public abstract class Shape implements Comparable
{
public abstract double area();
public abstract double perimeter();
public int compareTo( Object rhs )
{
Shape other = (Shape) rhs;
double diff = area() - other.area();
if( diff == 0 )
return 0;
else if( diff < 0 )
return -1;
else
return 1;
}
public double semiperimeter ()
{
return perimeter() / 2;
}
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 228
Selection Sort
Let a=[0:n − 1] and n=a.length. In selection sort we find the largest item
and put it in a[n − 1], then determine the largest of the remaining n − 1
elements and move it to a[n − 2], and so on.
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 229
◮ Example: Sort the array a[0:5]=[6,5,8,4,3,1]
[0] [1] [2] [3] [4] [5]
a 6 5 8 4 3 1
[0] [1] [2] [3] [4] [5]
a 6 5 1 4 3 8
[0] [1] [2] [3] [4] [5]
a 3 5 1 4 6 8
[0] [1] [2] [3] [4] [5]
a 3 4 1 5 6 8
[0] [1] [2] [3] [4] [5]
a 3 1 4 5 6 8
[0] [1] [2] [3] [4] [5]
a 1 3 4 5 6 8
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 230
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 231
The elements are
6 5 8 4 3 1
The sorted order is
1 3 4 5 6 8
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 232
Bubble Sort
In bubble sort (or the sinking sort) we make several bubbling passes
through the array. Each pass compares adjacent elements. The elements
are swaped in the case the one on the left is greater than the one on the
right. At the end of the bubbling pass, we are assured that the largest
element is in the right-most position.
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 233
◮ Example: Sort the array a[0:5]=[6,5,8,4,3,1]
[0] [1] [2] [3] [4] [5] [0] [1] [2] [3] [4] [5]
a 6 5 8 4 3 1 a 5 6 4 3 1 8
[0] [1] [2] [3] [4] [5] [0] [1] [2] [3] [4] [5]
a 5 6 8 4 3 1 a 5 6 4 3 1 8
[0] [1] [2] [3] [4] [5] [0] [1] [2] [3] [4] [5]
a 5 6 8 4 3 1 a 5 4 6 3 1 8
[0] [1] [2] [3] [4] [5] [0] [1] [2] [3] [4] [5]
a 5 6 4 8 3 1 a 5 4 3 6 1 8
[0] [1] [2] [3] [4] [5] [0] [1] [2] [3] [4] [5]
a 5 6 4 3 8 1 a 5 4 3 1 6 8
[0] [1] [2] [3] [4] [5]
a 5 6 4 3 1 8
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 234
[0] [1] [2] [3] [4] [5] [0] [1] [2] [3] [4] [5] [0] [1] [2] [3] [4] [5]
a 5 4 3 1 6 8 4 3 1 5 6 8 3 1 4 5 6 8
[0] [1] [2] [3] [4] [5] [0] [1] [2] [3] [4] [5] [0] [1] [2] [3] [4] [5]
a 4 5 3 1 6 8 3 4 1 5 6 8 1 3 4 5 6 8
[0] [1] [2] [3] [4] [5] [0] [1] [2] [3] [4] [5]
a 4 3 5 1 6 8 3 1 4 5 6 8
[0] [1] [2] [3] [4] [5]
a 4 3 1 5 6 8
It is like air bubbles rising in water, while the larger values sink to the
bottom of the array
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 235
public class BubbleSort
{
/** bubble largest element in a[0:n-1] to right */
private static void bubble(Comparable [] a, int n)
{
for (int i = 0; i < n - 1; i++)
if (a[i].compareTo(a[i+1]) > 0)
MyMath.swap(a, i, i + 1);
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 236
Insertion Sort
In insertion sort we traverse the list of items. For each item, we insert it
into its correct position amongst the items that we have already sorted.
We start with an array that contains just the first element, then we insert
the second element into the one-element array, we get a sorted array of
size 2. The insertion of the third element yields a sorted array of size 3,
and so on.
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 237
◮ Example: Sort the array a[0:5]=[6,5,8,4,3,1]
a 6 5 8 4 3 1
[0] [1] [2] [3] [4] [5]
a 5 6 8 4 3 1
[0] [1] [2] [3] [4] [5]
a 5 6 8 4 3 1
[0] [1] [2] [3] [4] [5]
a 4 5 6 8 3 1
[0] [1] [2] [3] [4] [5]
a 3 4 5 6 8 1
[0] [1] [2] [3] [4] [5]
a 1 3 4 5 6 8
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 238
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 239
Merge Sort
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 240
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 241
◮ Example: Sort the array a[0:7]=[5,3,8,6,7,2,4,1]
[0] [1] [2] [3] [4] [5] [6] [7]
5 3 8 6 7 2 4 1
5 3 8 6 7 2 4 1
Recursive calls
to mergeSort
5 3 8 6 7 2 4 1
5 3 8 6 7 2 4 1
3 5 6 8 2 7 1 4
3 5 6 8 1 2 4 7 Merge steps
1 2 3 4 5 6 7 8
[0] [1] [2] [3] [4] [5] [6] [7]
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 242
We can start with an empty list, SL, and we repeatedly remove the
smaller first item from the beginning of L or R and put it at the end of
SL. When both L and R are empty, SL will be a merged list sorted in
ascending order.
This merging process involves moving all n items into SL, and may involve
comparing as few as n/2 of them or as many as (n − 1) of them. Thus
merging is a linear time process known to require O(n) running time.
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 243
startOfFirst=0, endOfFirst=3, endOfSecond=7
c 3 5 6 8 1 2 4 7
d 1 2 3 4 5 6 7 8
[0] [1] [2] [3] [4] [5] [6] [7]
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 244
Complexity Analysis
Each mergeSort recursively calls itself twice. If the original call to merge-
Sort is at level 0, two calls to mergeSort occur at level 1 of the recursion.
Each of these calls then calls mergeSort twice, so four calls to mergeSort
occur at level 2 of the recursion, and so on.
The recursive calls continue until the array pieces each contain one item.
Then the recursion goes k = log n levels deep.
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 245
For example: For an array of eight items the levels of recursion are four.
8 Level 0
4 4 Level 1
2 2 2 2 Level 2
1 1 1 1 1 1 1 1 Level 3
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 246
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 247
We can eliminate virtually all the copying from b to a by merging alter-
natively from a to b and from b to a.
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 248
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 249
public static void merge(Comparable [] c, Comparable [] d,
int startOfFirst, int endOfFirst, int endOfSecond)
{
int first = startOfFirst, // cursor for first segment
second = endOfFirst + 1, // cursor for second
result = startOfFirst; // cursor for result
// merge until one segment is done
while ((first <= endOfFirst) && (second <= endOfSecond))
if (c[first].compareTo(c[second]) <= 0)
d[result++] = c[first++];
else
d[result++] = c[second++];
// take care of leftovers
if (first > endOfFirst)
for (int q = second; q <= endOfSecond; q++)
d[result++] = c[q];
else
for (int q = first; q <= endOfFirst; q++)
d[result++] = c[q];
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 250
Quick Sort
In quick sort you first choose an element in the array as a pivot element.
The pivot is used to separate the array into three partitions:
<p p ¸p
pivot
As a result, the elements in left, right and middle can be sorted inde-
pendently, and no merge is required following the sorting of left and
right.
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 251
Steps of the algorithm
• Select an element from a[0:length-1] for middle. This element is the
pivot.
• Partition the remaining elements into the segments left and right so
that
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 252
5 3 8 6 7 2 4 10 9 1
pivot pivot
5 3 2 4 1 6 8 7 10 9
2 1 3 5 4 6 7 8 10 9
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 253
Complexity Analysis
The worst-case computing time for quick sort is Θ(n2), and it is achieved,
for instance, when left is always empty.
If we are lucky and left and right are always of about the same size,
then the complexity is Θ(n log n). Therefore, the best-case complexity
of quick sort is Θ(n log n).
Surprisingly, the average complexity of quick sort is also Θ(n log n)
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 254
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 255
private static void quickSort(int leftEnd, int rightEnd)
{
if (leftEnd >= rightEnd) return;
int leftCursor = leftEnd, // left-to-right cursor
rightCursor = rightEnd + 1; // right-to-left cursor
Comparable pivot = a[leftEnd];
// swap elements >= pivot on left side
// with elements <= pivot on right side
while (true)
{
do
{ // find >= element on left side
leftCursor++;
} while (a[leftCursor].compareTo(pivot) < 0);
do
{ // find <= element on right side
rightCursor--;
} while (a[rightCursor].compareTo(pivot) > 0);
if (leftCursor >= rightCursor) break;
MyMath.swap(a, leftCursor, rightCursor);
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 256
a[leftEnd] = a[rightCursor];
a[rightCursor] = pivot;
quickSort(leftEnd, rightCursor - 1);
quickSort(rightCursor + 1, rightEnd);
}
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 257
Comparison of Sort Methods
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 258
Behind every able man, there are always other able men.
— Chinese Proverb
Estructuras de Datos
Sesión 8
Tree Data Structure
c 2011
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 260
Tree Data Structure
– governmental/company subdivisions,
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 261
Tree Terms
root
level 1
subtree
v level 2
y level 3
x
level 4
subtree
level 5
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 262
• x, y are children of v; v is a parent of x, y
• x, y are siblings
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 263
Binary Trees
A binary tree is a tree (possible empty) in which every element has
degree ≤ 2, except for the leaves.
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 264
Properties of Binary Trees
P1: Every binary tree with n elements, n > 0, has exactly n − 1 edges.
Proof: Each element (except the root) has one parent. ∃ exactly one
edge between each child and its parent. Hence, ∃n − 1 edges.
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 265
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 266
Full Vs Complete
2 3
4 5 6 7
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 267
2 3
4 5 6
Number the elements from 1 through 2h − k, starting from level 1
and proceed in a left-to-right fashion, for some k ≥ 1
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 268
P5: Let i, 1 ≤ i ≤ n, be the number assigned to an element v of a
complete binary tree. Then:
(i) If i = 1, then v is the root. If i > 1, then the parent of v has been
assigned the number ⌊i/2⌋.
(ii) If 2i > n, then v has no left child. Otherwise, its left child has been
assigned the number 2i.
(iii) If 2i + 1 > n, then v has no right child. Otherwise, its right child
has been assigned the number 2i + 1.
Proof: By induction on i.
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 269
Uses P5
1
A
2 3
B C
4 5 6 7
D E
1 2 3 4 5 6 7
A B C D E
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 270
Binary Tree Data Structure
Linked Representation
root
leftChild rightChild
data
data data
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 271
1) Pre-order: Visit-Left-Right
2) In-order: Left-Visit-Right
3) Post-order: Left-Right-Visit
4) Level order
B C
D E F
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 272
A
B C
D E F
1) Pre-order: ABDECF
2) In-order: DBEAFC
3) Post-order: DEBFCA
4) Level order: ABCDEF
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 273
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 274
Interface Definition of BinaryTree
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 275
// constructors
public BinaryTreeNode() {}
public BinaryTreeNode(Object theElement) {element = theElement;}
public BinaryTreeNode(Object theElement,
BinaryTreeNode theleftChild,
BinaryTreeNode therightChild)
{
element = theElement;
leftChild = theleftChild;
rightChild = therightChild;
}
// output method
public String toString() { return element.toString(); }
}
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 276
The Class LinkedBinaryTree
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 277
{
try
{
Class lbt = LinkedBinaryTree.class;
theAdd1 = lbt.getMethod("add1", paramType);
theOutput = lbt.getMethod("output", paramType);
}
catch (Exception e) {}
// exception not possible
}
// class methods
public static void output(BinaryTreeNode t)
{System.out.print(t.element + " ");}
public static void add1(BinaryTreeNode t) { ... }
{count++;}
public boolean isEmpty() { ... }
public Object root() { ... }
public void makeTree(Object root, Object left, Object right) { ... }
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 278
public BinaryTree removeLeftSubtree() { ... }
public BinaryTree removeRightSubtree() { ... }
public void preOrder(Method visit) { ... }
static void thePreOrder(BinaryTreeNode t) { ... }
public void inOrder(Method visit) { ... }
static void theInOrder(BinaryTreeNode t) { ... }
public void postOrder(Method visit) { ... }
static void thePostOrder(BinaryTreeNode t) { ... }
public void levelOrder(Method visit) { ... }
public void preOrderOutput() { ... }
public void inOrderOutput() { ... }
public void postOrderOutput() { ... }
public void levelOrderOutput() { ... }
public int size() { ... }
public int height() { ... }
static int theHeight(BinaryTreeNode t) { ... }
public static void main(String [] args) { ... }
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 279
/** set this to the tree with the given root and subtrees
* CAUTION: does not clone left and right */
public void makeTree(Object root, Object left,
Object right)
{
this.root = new BinaryTreeNode(root,
((LinkedBinaryTree) left).root,
((LinkedBinaryTree) right).root);
}
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 280
removeLeftSubtree
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 281
removeRightSubtree
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 282
preOrder
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 283
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 284
inOrder
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 285
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 286
postOrder
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 287
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 288
levelOrder
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 289
size
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 290
height
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 291
Test program
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 292
y.postOrderOutput();
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 293
Preorder sequence is
4 3 1 2
Inorder sequence is
1 3 2 4
Postorder sequence is
1 2 3 4
Level order sequence is
4 3 1 2
Number of nodes = 4
Height = 3
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 294
Binary Tree Application
Expression Trees
+ +
* / * d
a b c d - c
(a*b)+(c/d) a b
(((a-b)*c)+d)
infix form: a*b+c/d a-b*c+d
prefix form: +*ab/cd +*-abcd
postfix form: ab*cd/+ ab-c*d+
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 295
• postfix evaluation:
– Scan left-to-right
– If an operand is encountered, it is stacked in to a stack of operands
– If an operator is encountered, apply operator to the correct number
of operands in the top of the stack and replace them for the result
produced by the operator
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 296
If you are planning for a year, sow rice; if you are planning for a decade, plant trees;
if you are planning for a lifetime, teach people.
— Chinese Proverb
Estructuras de Datos
Sesión 9
Priority Queue Data Structure
c 2011
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 298
Priority Queue Data Structure
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 299
AbstractDataType MaxPriorityQueue
{
instances: finite collection of elements, each has a priority
operations:
isEmpty(): return true iff the queue is empty
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 300
The Interface MaxPriorityQueue
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 301
Representation of a MaxPriorityQueue
• As a Linear list
• As a Heap
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 302
Heaps
• Max tree (min tree): is a tree in which the value in each node is
greater (less) than or equal to those in its children.
• Max heap (min heap): is a max (min) tree that is also a complete
binary tree.
14 2
12 7 7 4
10 8 6 10 8 6
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 303
Representation of a Heap
• We can make use of property P5 to move from one node in the heap
to its parent or to one of its children
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 304
Insertion into a MaxHeap
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 305
20 20 20
15 2 15 2 15 5
14 10 14 10 5 14 10 2
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 306
Example: Insert 21 into heap
20 20 20
15 5 15 5 15 21
14 10 2 14 10 2 21 14 10 2 5
21
15 20
14 10 2 5
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 307
2) Delete the rightmost leaf at the highest level and put it in the root
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 308
Example: Remove Max element from heap
21 2
15 20 15 20 15 20
14 10 2 14 10 2 14 10
20
15 2
14 10
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 309
20 10
15 2 15 2 15 2
14 10 14 10 14
15 15
14 2 10 2
10 14
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 310
Initializing a MaxHead
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 311
Example: Initialize a heap with a[1:12] = [20, 12, 35, 15, 10, 7, 30,
14, 2, 1, 31, 80]
2 3
12 35
i
4 5 6 7
15 10 7 30
8 9 10 11 12
14 2 1 31 80
To heapify (i.e. make into a max heap) we begin with the last element
that has a child. This element must be at position i = ⌊n/2⌋=6
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 312
now examine the heap properties for the subtree rooted at node 5
1
20
2 3
12 35
i
4 5 6 7
15 10 80 30
8 9 10 11 12
14 2 1 31 7
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 313
1
20
2 3
12 35
i
4 5 6 7
15 31 80 30
8 9 10 11 12
14 2 1 10 7
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 314
now for the subtree rooted at node 3
1
20
i
2 3
12 35
4 5 6 7
15 31 80 30
8 9 10 11 12
14 2 1 10 7
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 315
1
20
i
2 3
12 80
4 5 6 7
15 31 35 30
8 9 10 11 12
14 2 1 10 7
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 316
now for the subtree rooted at node 1
i
1
20
2 3
31 80
4 5 6 7
15 12 35 30
8 9 10 11 12
14 2 1 10 7
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 317
1
80
2 3
31 35
4 5 6 7
15 12 20 30
8 9 10 11 12
14 2 1 10 7
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 318
The Class MaxHeap
// constructors
public MaxHeap(int initialCapacity) { ... }
public MaxHeap() { ... }
// methods
public boolean isEmpty() {return size == 0;}
public int size() {return size;}
public Comparable getMax() {return (size == 0) ? null : heap[1];}
public void put(Comparable theElement) { ... }
public Comparable removeMax() { ... }
public void initialize(Comparable [] theHeap, int theSize) { ... }
public String toString() { ... }
public static void main(String [] args) { ... }
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 319
Constructors
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 320
Insert
heap[currentNode] = theElement;
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 321
Delete
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 322
break; // yes
// no
heap[currentNode] = heap[child]; // move child up
currentNode = child; // move down a level
child *= 2;
}
heap[currentNode] = lastElement;
return maxElement;
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 323
Initialize
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 324
child++;
// can we put rootElement in heap[child/2]?
if (rootElement.compareTo(heap[child]) >= 0)
break; // yes
// no
heap[child / 2] = heap[child]; // move child up
child *= 2; // move down a level
}
heap[child / 2] = rootElement;
}
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 325
Test Program
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 326
Elements in array order are
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 327
Heap Application
Heap Sort
2) Extract (i.e. delete) elements from the heap one at a time. Each
deletion takes O(log n) time, so the total time is O(n log n)
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 328
public class HeapSort
{
public static void heapSort(Comparable [] a)
{
MaxHeap h = new MaxHeap();
h.initialize(a, a.length - 1);
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 329
1 2 3 4
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 330
You cannot prevent the birds of sorrow from flying over your head,
but you can prevent them from building nests in your hair.
— Chinese Proverb
Estructuras de Datos
Sesión 10
Dictionary Data Structure
c 2011
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 332
Dictionary Data Structure
Dictionary: collection of pairs of the form (k, e), where k is the key
and e is the element associated with the key k, supporting the following
operations:
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 333
AbstractDataType Dictionary
{
instances: collection of elements with distinct keys
operations:
get(k): return the element with key k
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 334
The Interface Dictionary
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 335
A dictionary is maintained as an ordered linear list (e0, e1, . . .), where the
eis are dictionary pairs in ascending order of key.
Using the linked representation, the class definition for a dictionary looks
as follow:
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 336
The Class SortedChain
// methods
public boolean isEmpty() {return size == 0;}
public Object get(Object theKey) { ... }
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 337
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 338
get
// verify match
if (currentNode != null &&
currentNode.key.equals(theKey))
// yes, found match
return currentNode.element;
// no match
return null;
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 339
remove
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 340
put
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 341
p.element = theElement;
return elementToReturn;
}
// no match, set up node for theElement
SortedChainNode q = new
SortedChainNode(theKey, theElement, p);
// insert node just after tp
if (tp == null) firstNode = q;
else tp.next = q;
size++;
return null;
}
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 342
Dictionary Data Structure
Skip List Representation
• Can we do better?
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 343
head tail
20 24 30 40 60 75 80
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 344
Insertions and Deletions
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 345
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 346
Example:
head tail
20 24 30 40 60 75 80
head tail
20 24 30 40 60 75 80
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 347
head tail
20 24 30 40 60 75 77 80
(c) 77 Inserted
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 348
Deletion of an element with key k
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 349
Assigning Levels
int level()
{
int lev = 0;
while (r.nextFloat() <= prob) lev++;
return (lev <= maxLevel) ? lev : maxLevel;
}
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 350
The Class SkipNode
// constructor
protected SkipNode(Object theKey, Object theElement,
int size)
{
key = (Comparable) theKey;
element = theElement;
next = new SkipNode [size];
}
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 351
// constructor
public SkipList(Comparable largeKey, int maxElements,
float theProb)
{ ... }
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 352
// methods
public boolean isEmpty() {return size == 0;}
public Object get(Object theKey) { ... }
SkipNode search(Object theKey) { ... }
int level() { ... }
public Object put(Object theKey, Object theElement)
{ ... }
public Object remove(Object theKey) { ... }
public static void main(String [] args) { ... }
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 353
Constructor
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 354
tailNode = new SkipNode (tailKey, null, 0);
last = new SkipNode [maxLevel + 1];
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 355
get
if (p.next[0].key.equals(theKey))
return p.next[0].element;
return null; // no matching element
}
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 356
search
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 357
put
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 358
lev = ++levels; last[lev] = headNode;
}
SkipNode y = new SkipNode (theKey,theElement,lev+1);
for (int i = 0; i <= lev; i++)
{ // insert into level i chain
y.next[i] = last[i].next[i];
last[i].next[i] = y;
}
size++;
return null;
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 359
remove
// update Levels
while (levels>0 && headNode.next[levels] == tailNode) levels--;
size--;
return p.element;
}
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 360
Dictionary Data Structure
Hash Table Representation
• Let K be the domain of all keys and let N be the set of natural
numbers. Then,
f : K → N . The element with key k is stored in position f (k) of the
hash table
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 361
• Search for the element. If found, then make the position f (k) of the
table empty
• Search for the element. If not found, i.e., position f (k) of the table
is empty, then place the element at that position
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 362
• If the key range is small, then we can easily implement hashing
E.g., let keys for a student record dictionary be 6 digit ID numbers,
and that we have 1000 students with IDs ranging from 771000 to
772000. Then, f (k) = k − 771000 maps IDs to positions 0 through
1000 of the hash table
E.g., keys are 12-character strings; each key has to be converted into
a numeric value by say mapping a blank to 0, an ’A’ to 1, . . ., and a
’Z’ to 26. This conversion maps the keys into integers in the range
[1, 2712 − 1]
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 363
• Find a hash function which maps several keys into the same position
of the hash table
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 364
• What happens if f (k1 ) = f (k2 ), for k1 6= k2, i.e., a so-called collision
has occurred
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 365
• Search starting from the home bucket f (k) and by examining succes-
sive buckets (and considering the table as circular) until one of the
following happens:
• In case 1, we have found the element we are looking for. In the other
two cases, the table doesn’t contain the requested element
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 366
Deleting the element with key k
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 367
// constructors
private HashEntry() {}
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 368
The Class HashTable
// constructors here
// methods
public boolean isEmpty() {return size == 0;}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 369
search
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 370
get
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 371
put
Yoan Pinzon 2016699 Estru
turas de Datos { Universidad Na
ional de Colombia 372
if (table[b].key.equals(theKey))
{ // duplicate, change table[b].element
Object elementToReturn = table[b].element;
table[b].element = theElement;
return elementToReturn;
}
else // table is full
throw new IllegalArgumentException("full table");
}
}
Yoan Pinzon 2016699 Estru turas de Datos { Universidad Na ional de Colombia 373