Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Todo algoritmo tiene una serie de características, entre otras que requiere una serie de
recursos, algo que es fundamental considerar a la hora de implementarlos en una
máquina. Estos recursos son principalmente:
· El tiempo: período transcurrido entre el inicio y la finalización del algoritmo.
· La memoria: la cantidad (la medida varía según la máquina) que necesita el algoritmo
para su ejecución.
- Notación O-grande
En general, el tiempo de ejecución es proporcional, esto es, multiplica por una constante
a alguno de los tiempos de ejecución anteriormente propuestos, además de la suma de
algunos términos más pequeños. Así, un algoritmo cuyo tiempo de ejecución sea T =
3N2 + 6N se puede considerar proporcional a N2. En este caso se diría que el algoritmo
es del orden de N2, y se escribe O(N2)
Los grafos definidos por matriz de adyacencia ocupan un espacio O(N2), siendo N el
número de vértices de éste.
La notación O-grande ignora los factores constantes, es decir, ignora si se hace una
mejor o peor implementación del algoritmo, además de ser independiente de los datos
de entrada del algoritmo. Es decir, la utilidad de aplicar esta notación a un algoritmo es
encontrar un límite superior del tiempo de ejecución, es decir, el peor caso.
A veces ocurre que no hay que prestar demasiada atención a esto. Conviene diferenciar
entre el peor caso y el esperado. Por ejemplo, el tiempo de ejecución del algoritmo
Quick Sort es de O(N2). Sin embargo, en la práctica este caso no se da casi nunca y la
mayoría de los casos son proporcionales a N·logN. Es por ello que se utiliza esta última
expresión para este método de ordenación.
1.1Collection
• Reduces programming effort because useful data structures and algorithms are
already written
• Increases performance because the provided collections are high-performance
implementations of useful data structures and algorithms
• Provides interoperability between unrelated APIs because a common language is
used to pass collections back and forth
• Reduces effort to learn APIs by eliminating the need to learn multiple ad hoc
collection APIs
Interfaces
The six interfaces pictured here make up the core of the collections framework. Each
defines a unique group of features and methods that define unique behaviors for each
object type.
The Collection interface is the base interface for the List and Set interfaces. The
interface includes any operations that are common to both descendant interfaces. A
collection defines a group of objects known as elements. Operations that can be
performed on the group include:
Note: Elements in any collection are stored using the Object class. This means a cast is
required when an element is retrieved from a collection.
The Set interface represents a group of elements that contains no duplicates. Each
element in the group is unique.
The SortedSet interface is a set of elements that are kept in ascending order. The
interface includes methods that take advantage of this ordering.
The List interface represents an ordered list of elements. Duplicate elements are
allowed. List objects provide control over where elements are inserted. In addition,
each element can be accessed through an index.
The Map interface represents a group of key/value pairs. Each object stored in a Map
interface has a key that uniquely identifies the object associated with it. Each value
stores an object and duplicate objects are allowed. Because the Map interface stores a
key and value pair and not individual objects, it does not inherit from the Collection
interface.
The SortedMap interface keeps the keys of the Map interface in a sorted order. This
interface also includes methods that take advantage of this ordering.
With the discussion of each interface's characteristics out of the way, you can now look
at some general implementations of collection interfaces.
The List Interface Implementations
There are two main implementations of the List interface, the ArrayList and
LinkedList classes.
The ArrayList class is used to create a dynamic growable array. Unlike a regular array,
which is a fixed sized, an ArrayList class grows as elements are added to the array
object.
1) import java.util.*;
2)
3) public class ReadArr{
4) public static void main(String[] args){
5) List myList = new ArrayList();
6)
7) // Populate the ArrayList
8) for (int i = 0; i < args.length ; i++){
9) myList.add(args[i]);
10) }
11)
12) //Print the ArrayList
13) for (int i = 0; i < myList.size(); i++){
14) System.out.println("Element "+ i + ": "+
myList.get(i));
15) }
16) }
17)}
One of the features of collections is a built-in way of stepping through the contents of a
collection. In the previous example, a for loop is used to print out the contents of the
ArrayList class. With a collection, the Iterator and ListIterator interfaces can be
used instead.
An Iterator object provides a standard way for stepping through each element in a
collection. The following example replaces the for loop with an Iterator object.
1) import java.util.*;
2)
3) public class ReadArrIt{
4) public static void main(String[] args){
5) List myList = new ArrayList();
6)
7) // Populate the ArrayList
8) for (int i = 0; i < args.length ; i++){
9) myList.add(args[i]);
10) }
11)
12) //Print the ArrayList
13) String temp = "";
14) Iterator i = myList.iterator();
15) while(i.hasNext()){
16) temp = (String) i.next();
17) System.out.println("Element: "+ temp);
18) }
19) }
20)}
An Iterator interface is defined on line 14. The call to the iterator method creates
an Iterator object i. The hasNext method on line 15 returns true if there are more
elements to step through. The next method in line 16 retrieves the element currently
pointed to and moves the object pointer to the next object. Remember, elements in a
collection are stored using the Object class and a cast is required to retrieve the object
from a collection.
The use of the temp variable is unnecessary in this example. The use of the variable
illustrates the normal steps required to retrieve an object. Often, you would be doing
more than simply printing a value.
The ListIterator interface provides additional options for stepping through a list. The
ListIterator interface includes methods that access the next item in the list or the
previous item in the list. This allows traversal in either direction. Also, the index is
accessible through the nextIndex or previousIndex methods. The following example
demonstrates the use of a ListIterator interface:
1) import java.util.*;
2)
3) public class ReadArrLIt{
4) public static void main(String[] args){
5) List myList = new ArrayList();
6)
7) // Populate the ArrayList
8) for (int i = 0; i < args.length ; i++){
9) myList.add(args[i]);
10) }
11)
12) //Print the ArrayList
13) String temp = "";
14) int index = 0;
15) ListIterator i = myList.listIterator();
16) while(i.hasNext()){
17) index = i.nextIndex();
18) temp = (String) i.next();
19) System.out.println("Element "+ index + " :" +
temp);
20) }
21) }
22)}
The other general purpose implementation of List interface is a LinkedList class. The
LinkedList class is an implementation of a doubly linked list. This implementation is a
good choice if you need to iterate through a list and delete elements from the list's
interior. However, it does take more time to access individual elements in a LinkedList
class than an ArrayList class.
1) import java.util.*;
2)
3) public class ReadArrLinked{
4) public static void main(String[] args){
5) List myList = new LinkedList();
6)
7) // Populate the ArrayList
8) for (int i = 0; i < args.length ; i++){
9) myList.add(args[i]);
10) }
11)
12) //Print the ArrayList
13) String temp = "";
14) Iterator i = myList.iterator();
15) while(i.hasNext()){
16) temp = (String) i.next();
17) System.out.println("Element: "+ temp);
18) }
19) }
20)}
Notice the only change from the previous example is the new statement on line 5.
Otherwise, the program is unchanged.