Вы находитесь на странице: 1из 4871

Bega mega data Bega mega data Scribd

Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:
1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table
Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5
Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search
Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table
Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table
Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10
3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social MediaBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10
3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google PlayBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:
-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow
brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoicesBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?


All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments
auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved


Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
TermsBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments
auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto
Most popular in Difference Between
Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership
Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

5th Floor, A-118,


Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}
// Driver method to test above method
public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples
?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo


Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member
Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.Bega mega data Bega
mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare eleBega mega data
Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:
-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10
3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications


Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications


Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase helpBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java
TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?


All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments
auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved


Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
ment din vector, etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Unde este gre?eala?


Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Copyright � 2020 Scribd Inc..Browse Books.Site Directory.


Site Language:
English
Change Language

Scribd - Download on the App Store


Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto
Most popular in Difference Between
Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking
Most visited in Java
Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi
structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points
HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}
// Driver method to test above method
public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples
?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase


structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social MediaBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points
HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}
// Driver method to test above method
public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples
?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA
Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)
Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene


structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date


Don't want to upload?
Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google PlayBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto
Most popular in Difference Between
Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved


Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoicesBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
TermsBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:
1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

5th Floor, A-118,


Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.Bega mega data Bega
mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java
TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?


All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments
auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved


Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare eleBega mega data
Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points
HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate


structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document
ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos
@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase helpBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}
// Driver method to test above method
public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples
?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}
Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
ment din vector, etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Unde este gre?eala?


Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Copyright � 2020 Scribd Inc..Browse Books.Site Directory.


Site Language:
English
Change Language

Scribd - Download on the App Store


Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:
1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table
Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10
3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search
Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table
Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5
Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10
3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social MediaBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10
3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google PlayBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java
thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications


Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoicesBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java
TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?


All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments
auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved


Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
TermsBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?


All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments
auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto
Most popular in Difference Between
Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

5th Floor, A-118,


Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}
// Driver method to test above method
public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples
?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase


structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member
Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.Bega mega data Bega
mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}
// Driver method to test above method
public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples
?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}
Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare eleBega mega data
Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:
-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications


Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search
Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table
Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase helpBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java
TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow
brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?


All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos
@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
ment din vector, etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Unde este gre?eala?


Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Copyright � 2020 Scribd Inc..Browse Books.Site Directory.


Site Language:
English
Change Language

Scribd - Download on the App Store


Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments
auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points
HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking
Most visited in Java
Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi
structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points
HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}
// Driver method to test above method
public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples
?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA
Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)
Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene


structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date


Don't want to upload?
Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social MediaBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points
HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA
Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)
Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene


structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date


Don't want to upload?
Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google PlayBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto
Most popular in Difference Between
Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos
@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoicesBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}
// Driver method to test above method
public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples
?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}
Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
TermsBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:
1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

5th Floor, A-118,


Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.Bega mega data Bega
mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java
TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow
brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?


All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos
@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare eleBega mega data
Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto
Most popular in Difference Between
Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate


structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document
ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking
Most visited in Java
Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo


Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase helpBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}
// Driver method to test above method
public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples
?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}
Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU
Aproximativ 783 rezultate (0,30 secunde)
Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
ment din vector, etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Unde este gre?eala?


Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Copyright � 2020 Scribd Inc..Browse Books.Site Directory.


Site Language:
English
Change Language

Scribd - Download on the App Store


Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10
3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table
Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5
Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved


Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10
3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social MediaBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:
-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10
3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications


Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google PlayBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java
thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications


Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoicesBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java
TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow
brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?


All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos
@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
TermsBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?


All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments
auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved


Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

5th Floor, A-118,


Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}
// Driver method to test above method
public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples
?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase


structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.Bega mega data Bega
mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}
// Driver method to test above method
public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples
?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}
Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU
Aproximativ 783 rezultate (0,30 secunde)
Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare eleBega mega data
Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java
thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search
Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table
Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications


Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search
Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table
Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5
Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase helpBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow
brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java
TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos
@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
ment din vector, etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Unde este gre?eala?


Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Copyright � 2020 Scribd Inc..Browse Books.Site Directory.


Site Language:
English
Change Language

Scribd - Download on the App Store


Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?


All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments
auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points
HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points
HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA
Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)
Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene


structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date


Don't want to upload?
Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social MediaBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points
HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate


structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document
ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google PlayBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto
Most popular in Difference Between
Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos
@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoicesBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}
// Driver method to test above method
public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples
?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}
Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU
Aproximativ 783 rezultate (0,30 secunde)
Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
TermsBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

5th Floor, A-118,


Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.Bega mega data Bega
mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow
brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java
TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos
@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare eleBega mega data
Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto
Most popular in Difference Between
Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking
Most visited in Java
Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++


structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music
Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking
Most visited in Java
Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}
// Driver method to test above method
public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples
?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo


Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member
Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase helpBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}
Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU
Aproximativ 783 rezultate (0,30 secunde)
Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
ment din vector, etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Unde este gre?eala?


Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Copyright � 2020 Scribd Inc..Browse Books.Site Directory.


Site Language:
English
Change Language

Scribd - Download on the App Store


Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10
3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table
Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10
3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved


Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:
-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10
3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications


Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social MediaBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:
-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications


Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google PlayBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:
1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search
Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table
Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoicesBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow
brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java
TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos
@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
TermsBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java
TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?


All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments
auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved


Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

5th Floor, A-118,


Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}
// Driver method to test above method
public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples
?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA
Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)
Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene


structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date


Don't want to upload?
Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.Bega mega data Bega
mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}
Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU
Aproximativ 783 rezultate (0,30 secunde)
Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare eleBega mega data
Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java
thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search
Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table
Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5
Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications


Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table
Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5
Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase helpBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java
TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow
brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
ment din vector, etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Unde este gre?eala?


Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Copyright � 2020 Scribd Inc..Browse Books.Site Directory.


Site Language:
English
Change Language

Scribd - Download on the App Store


Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?


All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points
HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points
HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points
HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate


structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document
ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social MediaBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto
Most popular in Difference Between
Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate


structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document
ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google PlayBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto
Most popular in Difference Between
Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking
Most visited in Java
Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo


Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoicesBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}
Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU
Aproximativ 783 rezultate (0,30 secunde)
Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
TermsBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}
// Driver method to test above method
public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples
?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}
Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

5th Floor, A-118,


Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.Bega mega data Bega
mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java
TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow
brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare eleBega mega data
Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto
Most popular in Difference Between
Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking
Most visited in Java
Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++


structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music
Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}
// Driver method to test above method
public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples
?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase


structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member
Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase helpBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}
Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved


Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
ment din vector, etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Unde este gre?eala?


Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Copyright � 2020 Scribd Inc..Browse Books.Site Directory.


Site Language:
English
Change Language

Scribd - Download on the App Store


Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:
-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10
3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10
3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos
@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:
-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications


Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social MediaBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java
thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search
Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table
Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications


Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google PlayBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:
1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search
Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table
Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5
Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoicesBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java
TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow
brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
TermsBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java
TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow
brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?


All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos
@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

5th Floor, A-118,


Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA
Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)
Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene


structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date


Don't want to upload?
Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.Bega mega data Bega
mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}
Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved


Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare eleBega mega data
Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:
1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table
Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5
Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search
Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table
Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table
Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10
3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase helpBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow
brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
ment din vector, etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Unde este gre?eala?


Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Copyright � 2020 Scribd Inc..Browse Books.Site Directory.


Site Language:
English
Change Language

Scribd - Download on the App Store


Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java
TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points
HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points
HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto
Most popular in Difference Between
Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate


structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document
ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social MediaBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto
Most popular in Difference Between
Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking
Most visited in Java
Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++


structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music
Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google PlayBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments
auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking
Most visited in Java
Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}
// Driver method to test above method
public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples
?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo


Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member
Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoicesBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}
Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved


Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
TermsBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}
// Driver method to test above method
public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples
?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}
Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU
Aproximativ 783 rezultate (0,30 secunde)
Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

5th Floor, A-118,


Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications


Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.Bega mega data Bega
mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow
brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare eleBega mega data
Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto
Most popular in Difference Between
Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking
Most visited in Java
Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi
structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points
HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}
// Driver method to test above method
public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples
?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase


structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase helpBega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved


Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
ment din vector, etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Unde este gre?eala?


Tema!
lect. dr. Gabriela Trimbitas 28
Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Copyright � 2020 Scribd Inc..Browse Books.Site Directory.


Site Language:
English
Change Language

Scribd - Download on the App Store


Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language

Purchase help
AdChoices
Publishers
LEGAL
Terms
Privacy
Copyright
Social Media
Scribd - Download on the App Store
Scribd - Get it on Google Play
Copyright � 2020 Scribd Inc..Browse Books.Site Directory.
Site Language:
English
Change Language
Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}
Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:
-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10
3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeniNDAMENTALI IN JAVA , APLICATII de
DOINA LOGOFATU , 2007. Stoc epuizat la 04-07-2016, pret 10,00 Lei ...
Anun?uri despre rezultatele filtrate
Este posibil ca unele rezultate sa fi fost eliminate conform legisla?iei privind
protec?ia datelor din Europa. Afla?i mai multe
Navigare �n pagini
1
2
3
4
5
6
7
8
9
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfiden?ialitateTermeni
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos
@geeksforgeeks, Some rights reserved

Contact Us
LEARN
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
PRACTICE
Courses
Company-wise
Topic-wise
How to begin?
CONTRIBUTE
Write an Article
Write Interview Experience
Internships
Videos

@geeksforgeeks, Some rights reserved

Change Language
Learn more about Scribd Membership

Home
Saved
Bestsellers
Books
Audiobooks
Snapshots
Magazines
Documents
Sheet Music

Once you upload an approved document, you will be able to download the document

ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de Date

Don't want to upload?


Get unlimited downloads as a member

Sign up now
You've uploaded 0 of the 1 required documents.
Error:Sorry, sd2010A4.pdf already exists on Scribd, please upload new content that
other Scribd users will find valuable. Eg. class notes, research papers,
presentations...
Upload 1 Document to Download
Upload your original presentations, research papers, class notes, or other
documents to download ARTA PROGRAMARII in JAVA Vol.ii Algoritmi Si Structuri de
Date
Select Documents To Upload
or drag & drop
Supported file types: pdf, txt, doc, ppt, xls, docx, and more. By uploading, you
agree to our Scribd Uploader Agreement
Footer Menu
ABOUT
About Scribd
Press
Our blog
Join our team!
Contact Us
Invite Friends
Gifts
SUPPORT
Help / FAQ
AccessibilityCoada cu prioritati
lect. dr. Gabriela Trimbitas 1
Am studiat urmatoarele TAD :
?Stiva: Principiu de cautare LIFO;
?Coada: Principiu de cautare FIFO;
?Tabela de simboluri (o coada generalizata �n care �nregistrarile au chei):
Principiu
de cautare : gaseste �nreistrarea a carei cheie este egala cu o cheie data, daca
exista.
Observa?ie: Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar
diferite, care rezulta ca un produs al examinarii atente a programelor client ?i
a performan?ei la implementari
lect. dr. Gabriela Trimbitas 2
Observa?ie:
Pentru multe aplica?ii, elementele abstracte pe care le prelucreaza sunt unice, o
calitate care ne determina sa luam �n considerare ?i modificarea ideii noastre
despre modul �n care stive, cozi FIFO ?i alte TAD-uri generalizate ar trebui sa
func?ioneze. �n mod concret, trebuie luat �n considerare efectul de a schimba
specifica?iile la stive, cozi FIFO ?i cozi generalizate pentru a interzice obiecte
duplicat �n structura de date.
Exemple:O companie care men?ine o lista de adrese de clien?i ar putea
dori sa �ncerce sa creasca lista prin efectuarea opera?iunilor de inserare
din alte liste adunate din mai multe surse, dar nu ar vrea ca lista sa sa
creasca pentru o opera?ie de inserare, care se refera la un client deja aflat
pe lista. Acela?i principiu se aplica �ntr-o varietate de aplica?ii. Pentru un
alt exemplu, luam �n considerare problema de rutare a un mesaj printr-o
re?ea complexa de comunica?ii. Am putea �ncerca sa trecem simultan prin
mai multe cai �n re?ea, dar exista doar un singur mesaj, astfel �nc�t orice
nod din re?ea ar dori/trebui sa aiba un singur exemplar din mesaj �n
structurile sale interne de date.
lect. dr. Gabriela Trimbitas 3
O abordare pentru rezolvarea acestei situa?ii este de a lasa la latitudinea clien?
ilor
sarcina de a se asigura ca elementele duplicat nu sunt prezente �n TAD, o sarcina
pe
care clien?ii probabil ar putea-o efectua cu ajutorul unui TAD diferit. Dar, din
moment ce scopul unei TAD este de a oferi clientilor solu?ii �curate� la problemele
de aplica?ii, am putea decide ca detectarea ?i rezolvarea duplicatelor este o parte
a
problemei pe care TAD ar trebui sa o rezolve.
Politica de a interzice elemente cu dubluri este o schimbare �n abstractizare:
interfa?a,
numele opera?iilor ?i a?a mai departe pentru un astfel de TAD sunt acelea?i cu cele
pentru TAD-ul corespunzator fara restrictii, dar comportamentul implementarii se
schimba �n mod fundamental. �n general, ori de c�te ori vom modifica specifica?iile
al unui TAD, vom ob?ine un TAD complet nou - unul care are proprieta?i complet
diferite.
Fiecare TAD da nastere unui numar de TAD-uri �nrudite, dar diferite, care
rezulta ca un produs al examinarii atente a programelor client ?i a
performan?ei la implementari
lect. dr. Gabriela Trimbitas 4
Vom considera acum un alt caz de coada: Coada cu prioritati.
MULTE APLICATII cer ca sa prelucram �nregistrari cu cheile �n ordine, dar nu
neaparat �n ordine complet sortata ?i nu neaparat toate o data. De multe ori,
vom colecta un set de �nregistrari, apoi prelucram �nregistrarea cu cea mai mare
cheie, apoi poate colectam mai multe �nregistrari, apoi prelucram cea cu cheia
de curenta cea mai mare ?i a?a mai departe. O structura de date adecvata �ntr-un
astfel de situatie suporta opera?iunile de: introducerea unui nou element ?i
?tergerea celui mai mare element. O astfel de structura de date se nume?te
o coada cu prioritati. Folosirea cozilor cu prioritati este similara cu utilizarea
cozilor FIFO (?terge cea mai veche) ?i stivelor LIFO (?terge cele mai noi), dar
punerea lor �n aplicare �n mod eficient este mai dificila. Coada cu prioritati este
cel mai important exemplu de TAD coada generalizata. De fapt, coada cu
prioritati este o generalizare buna a stivei ?i cozii, pentru ca putem implementa
aceste structuri de date cu cozile cu prioritati, folosind atribuiri adecvate de
prioritati.
lect. dr. Gabriela Trimbitas 5
Defini?ie: O coada cu prioritati este o structura de date de �nregistrari cu
chei care accepta doua opera?ii de baza: introduce un nou articol ?i ?terge
elementul cu cea mai mare cheie.
Unul dintre principalele motive pentru care multe implementari de cozi cu
priorita?i sunt at�t utile, este flexibilitatea �n a permite programelor de
aplica?ii client de a efectua o varietate de diferite opera?ii pe seturi de
�nregistrari cu chei.
lect. dr. Gabriela Trimbitas 6
Vrem sa construim ?i sa actualizam o SD care con?ine �nregistrari cu chei
numerice (priorita?i) care suporta unele dintre urmatoarele opera?iuni:
Construct: Construirea unei cozi cu prioritati din N articole date;
Insert: Inserarea unui nou element;
Remove=Delete the maximum: ?tergerea elementului maxim;
Change the priority: Schimbarea priorita?ii unui element specificat arbitrar;
Delete: ?tergerea unui element specificat arbitrar;
Join doua cozi de prioritate �ntr-una singura.
lect. dr. Gabriela Trimbitas 7
Observa?ii:
1. �n cazul �n care �nregistrarile pot avea chei duplicate, vom lua drept "maxim"
�orice
�nregistrare cu cea mai mare valoare de cheie�.
2. Ca ?i �n multe alte structuri de date, avem, de asemenea, nevoie sa adaugam la
acest
set opera?iile standard de ini?ializare, de testare ifempty ?i, probabil, destroy ?
i copy
3. Exista o suprapunere �ntre aceste opera?ii, iar uneori este mai eficient sa se
defineasca alte opera?ii similare, de exemplu, anumi?i clien?i poate doresc �n mod
frecvent sa gaseasca elementul maxim din coada cu prioritati, fara �nsa a-l sterge
sau, am putea avea o opera?ie de �nlocuire a elementului maxim cu un nou element
care se poate efectua ca: Remove + Insert sau Insert+ Remove, dar �n mod normal,
vom ob?ine cod mai eficient , prin implementarea unor astfel de opera?ii �n mod
direct, cu condi?ia ca acestea sa fie necesare ?i precis specificate !
(Remove+Insert?Insert+ Remove).
4. Pentru unele aplica?ii, ar putea fi ceva mai convenabil de a comuta si a lucra
cu
elementul minim, mai degraba dec�t cu cel maxim. Noi ram�nem �n primul r�nd, la
cozile cu prioritati care sunt orientate spre accesarea elementului cu cheia
maxima.
lect. dr. Gabriela Trimbitas 8
Coada cu prioritati este un prototip de tip abstract de date (TAD) (vezi cursul 3):
Reprezinta un set bine definit de opera?iuni asupra datelor, ?i ofera o abstrac?ie
convenabila care permite sa se separe programele de aplica?ii (clien?i) de
diversele
implementari pe care le vom lua �n considerare �n acest curs.
Aceasta interfa?a define?te opera?iile pentru cel mai simplu tip de coada cu
prioritati : ini?ializare, testare daca este vida, inserare un element nou,
stergere cel mai mare element. Implementari elementare ale acestor func?ii,
utiliz�nd array-uri ?i liste inlantuite pot necesita �n cel mai defavorabil
caz, timp liniar, dar vom vedea implementari �n acest curs �n care toate
opera?iunile sunt garantate pentru a rula �n timp propor?ional cu logaritmul
numarului de elemente din coada cu prioritati. Argumentul lui PQinit specifica
numarul maxim de elemente acceptate �n coada cu prioritati.
void PQinit(int);
int PQempty();
void PQinsert(Item);
Item PQdelmax() ;
lect. dr. Gabriela Trimbitas 9
Implementari elementare
Implementari ale cozilor cu prioritati folosind:
? O lista nesortata (ordonata) �n raport cu cheile elementelor;
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? O lista sortata (ordonata) �n raport cu cheile elementelor
� reprezentare secventiala pe tablou (vector dinamic) .
� reprezentare �nlantuita (simplu/dublu, folosind alocare
dinamica/alocare statica)
? Structura de heap.
Avantaje - Dezavantaje
lect. dr. Gabriela Trimbitas 10
O implementare care utilizeaza un array neordonat ca structura de date de baza.
Opera?ia gaseste maxim este implementat prin parcurgerea array-ului pentru a
gasi valoarea maxima, apoi schimba elementul maxim cu ultimul element ?i
decrementeaza dimensiunea cozii.
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc(maxN*sizeof(Item)); N=0;}
int PQempty() { return N == 0; }
void PQinsert(Item v)
{ pq[N++] = v; }
Item PQdelmax ()
{ int j, max = 0;
for (j = 1; j < N; j ++ )
if (less(pq[max] , pq[j])) max = j;
exch(pq[max] , pq[N]);
return --N;
}
lect. dr. Gabriela Trimbitas 11
Exemplu de coada cu
prioritati ca array pentru
o secventa de operatii:
litera = insereaza
* = sterge maximum
lect. dr. Gabriela Trimbitas 12
(Sedgewick)
Complexitatea operatiilor cozilor cu prioritati �n cazul cel mai defavorabil
lect. dr. Gabriela Trimbitas 13
Structura de heap
O structura de date simpla numita heap (gramada) este o SD care poate sprijini
eficient opera?iile de baza ale cozii cu prioritati.
�ntr-un heap, �nregistrarile sunt stocate �ntr-un array, astfel �nc�t fiecare cheie
este garantat mai mare dec�t cheile de pe doua pozi?ii determinate. La r�ndul
sau, fiecare dintre aceste chei trebuie sa fie mai mare dec�t alte doua chei ?i a?a
mai departe. Aceasta ordonare este u?or de �nteles daca privim cheile ca fiind
�ntr-o structura de arbore binar; arcele de la fiecare cheie duc la cele doua chei
cunoscute a fi mai mici.
lect. dr. Gabriela Trimbitas 14
lect. dr. Gabriela Trimbitas 15
Un arbore binar este complet plin, daca acesta este de �nal?ime h , ?i are 2
h+1
-1
noduri .
Un arbore binar de �nal?ime h, este complet daca ?i numai daca :
? este gol sau
? subarborele st�ng este complet de �nal?ime h - 1 ?i subarborele sau drept este
complet plin de �nal?ime h - 2 sau
? subarborele st�ng este complet plin de �nal?ime h - 1 ?i subarborele sau drept
este complet de �nal?ime h - 1
Un arbore complet este umplut de la st�nga :
? toate frunzele sunt pe acela?i nivel sau pe doua adiacente ?i
? toate nodurile de pe nivelul cel mai scazut sunt c�t mai spre st�nga posibil
Defini?ie 1: Un arbore este ordonat ca heap �n cazul �n care cheia din
fiecare nod este mai mare sau egala cu cheile �n to?i copiii nodului
(daca este cazul). Echivalent, cheia �n fiecare nod al unui arbore
ordonat ca heap, este mai mica dec�t sau egala cu cheia parintelui
acelui nod (daca este cazul)
Defini?ia 2: Un heap este o multime de noduri cu chei aranjate �ntr-un
arbore binar complet ordonat ca heap, reprezentat ca array.
Proprietate 1: Nici un nod al unui arbore ordonat ca heap nu are o cheie
mai mare decat cheia din radacina.
lect. dr. Gabriela Trimbitas 16
(Sedgewick)
lect. dr. Gabriela Trimbitas 17
Remember
Prin traversarea unui arbore binar vom �ntelege parcurgerea tuturor nodurilor
arborelui, trec�nd o singura data prin fiecare nod.
�n functie de ordinea (disciplina) de vizitare a nodurilor unui arbore binar,
exista
trei moduri de baza de traversare:
? �n preordine: viziteaza mai �nt�i nodul (radacina), apoi subarborele st�ng si
dupa aceea subarborele drept
? �n inordine: viziteaza mai �nt�i subarborele st�ng , apoi nodul (radacina) si
dupa aceea subarborele drept
? �n postordine: viziteaza mai �nt�i subarborele st�ng , apoi subarborele drept
si dupa aceea nodul (radacina)
New !
? level order: nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos
L�nga fiecare nod din arborele pe care l-am reprezentat se afla c�te un numar,
reprezent�nd pozitia �n
vector pe care ar avea-o nodul respectiv. Pentru cazul considerat, vectorul
echivalent ar fi
H = (X T O G S M N A E R A I ).
Se observa ca nodurile sunt parcurse de la st�nga la dreapta si de sus �n jos. O
proprietate necesara
pentru ca un arbore binar sa se poata numi heap este ca toate nivelurile sa fie
complete, cu exceptia
ultimului, care se completeaza �ncep�nd de la st�nga si continu�nd p�na la un anume
punct. De aici
deducem ca �naltimea unui heap cu N noduri este lgn. Reciproc, numarul de noduri
ale unui heap de
�naltime h este
Din aceasta organizare rezulta ca parintele unui nod k > 1 este nodul [k/2], iar
copii nodului k sunt
nodurile 2k si 2k+1. Daca 2k = N, atunci nodul 2k+1 nu exista, iar nodul k are un
singur fiu; daca 2k >
N, atunci nodul k este frunza si nu are nici un copil.
lect. dr. Gabriela Trimbitas 18
(Sedgewick)
lect. dr. Gabriela Trimbitas 19
Bottom-up heapify
fixUp(Item a[], int k)
{
while (k > 1 && less(a[k/2], ark]))
{ exch(a[k], a[k/2]); k k/2;}
}
modifying ~heapifying fixing
Top-down heapify
fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ j = 2*k;
if (j < N && less(a[j], a[j+l])) j++;
if (!less(a[k], a[j])) break;
exch(a[k], a[j]); k = j;
}
}
lect. dr. Gabriela Trimbitas 20
Un heap poate fi folosit ca o coada cu prioritati: elementul cu cea mai
mare prioritate este �n radacina ?i �n mod trivial este extras . Dar daca
radacina este ?tearsa, au ramas doi subarbori ?i trebuie re-creat eficient un
singur arbore cu proprietatea de heap .
Proprietate 2: Operatiile insert ?i delete maximum �ntr-un TAD coada cu
prioritati cu n elemente implementata cu heap se efectueaza �n timp
O(logn ). (insert numar comparatii = lgn, iar deletemax = 2lgn)
Proprietate 3: Operatiile change priority, replace the maximum ?i delete
�ntr-un TAD coada cu prioritati cu n elemente pot fi implementate cu
arbori ordonati cu structura de heap astfel inc�t sa nu se efectueze mai
mult de 2lgn comparatii.
lect. dr. Gabriela Trimbitas 21
Construirea top-down a unui heap
//Coada cu prioritati implementata
//prin heap
#include <stdlib.h>
#include "Item.h"
static Item *pq;
static int N;
void PQinit(int maxN)
{ pq = malloc�maxN+1)*sizeof(Item));
N = 0; }
int PQemptyO { return N == 0; }
void PQinsert(Item v)
{
pq[++N] = v;
fixUp(pq, N);
}
Item PQdelmax ()
{
exch(pq[l], pq[N]);
fixDown(pq, 1, N-1);
return pq[N--];
}
(Sedgewick)
lect. dr. Gabriela Trimbitas 22
Heapsort
Pentru a sorta un subarray a [l], �, a [r] folosind un ADT coada cu
prioritati, noi pur ?i simplu vom folosi PQinsert pentru a pune toate
elementele �n coada cu prioritati, iar apoi utilizam PQdelmax pentru a le
elimina, �n ordine descrescatoare. Acest algoritm de sortare se executa
�n timp propor?ional cu nlgn, dar folose?te spa?iu suplimentar
propor?ional cu numarul de elemente care trebuie sortate (pentru coada
cu prioritati).
void PQsort(Item a[], int 1, int r)
{ int k;
Pqinit();
for (k = 1; k <= r; k++) PQinsert(a[k]);
for (k = r; k >= 1; k--) a[k] = PQdelmax();
}
Costul total este < lgn + � + lg2 + lg1 = lgn!
(Stirling)
lect. dr. Gabriela Trimbitas 23
Construire Top-Down a heapului: ASORTINGEXAMPLE
(Sedgewick)
lect. dr. Gabriela Trimbitas 24
Construire Bottom-Up a heapului: ASORTINGEXAMPLE
(Sedgewick)
Proprietate 4: Construirea Bottom-Up a heapului necesita un timp liniar.
Proprietate 5: Heapsort folose?te mai putin de nlgn comparatii pentru a sorta n
elemente.
lect. dr. Gabriela Trimbitas 25
Sortare din heapul cunstruit =>AAEEGILMNOPRSTX
(Sedgewick)
lect. dr. Gabriela Trimbitas 26
(Sedgewick)
lect. dr. Gabriela Trimbitas 27
Heap-uri indirecte
Dec�t a rearanja cheile �ntr-un domeniu, este mai avantajos sa lucram cu un domeniu
de indici p care se refera la un array a. a[ p [ k ]] este, prin urmare,
�nregistrarea
corespunzatoare a elementului k al heap-ului, pentru k �ntre 1 ?i N. In plus
utilizam un
alt array q �n care este stocata pozitia �n heap al celui de-al k-lea element din
array.
Astfel, ne-am permite ?i opera?iile de change/ schimbare ?i de delete/?tergere .
Prin
urmare , numarul 1, este �nregistrarea �n q pentru cel mai mare element din vector,
etc.
Daca dorim, de exemplu, sa schimbam valoarea unui a[ k ], putem gasi pozi?ia �n
heap
�n q [ k ], iar dupa modificare se va folosi upheap sau downheap. �n figura, sunt
date
valorile din acesti vectori pentru heapul nostru bottom-up (slide 24) ; observam ca
p [ q [ k ] ] = q [ p [ k ] ] = k pentru orice k de la 1 la N.
Unde este gre?eala?
Tema!
lect. dr. Gabriela Trimbitas 28Bega mega data Bega mega data Scribd
Search
Search
Search
Upload
ENGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java
thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy PolicyGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search
Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table
Real Life Applications

Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
COMPANY
About Us
Careers
Privacy Policy
Contact Us
LEARN
Algorithms
Data Structures
Languages
CS SubjectsGeeksforGeeks
Skip to content
Tutorialskeyboard_arrow_down Studentskeyboard_arrow_down Courses
Custom Search

Login
Hire with us!
LinkedHashMap in Java
LinkedHashMap clear() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap and LinkedHashSet in Java
Design a data structure for LRU Cache
Hashing in Java
Differences between TreeMap, HashMap and LinkedHashMap in Java
perm_identity
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java

TreeMap, HashMap and LinkedHashMap: What�s Similar?

All offer a key->value map and a way to iterate through the keys. The most
important distinction between these classes is the time guarantees and the ordering
of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map
interface, and represents mapping from unique key to values.
Key Points

HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys,
though, the ordering of the keys is essentially arbitrary. It is implemented by an
array of linked lists.
Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by
their insertion order. It is implemented by doubly-linked buckets.
Syntax:
public class LinkedHashMap extends HashMap
0implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you
need to iterate through the keys in sorted order, you can. This means that keys
must implement the Comparable interface. TreeMap is implemented by a Red-Black
Tree.
Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural
order of its key).
Hashtable: �Hashtable� is the generic name for hash-based maps.
Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
filter_none
edit
play_arrow

brightness_4
// Java program to print ordering
// of all elements using HashMap
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
// This function prints ordering of all elements
static void insertAndPrint(AbstractMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}

// Driver method to test above method


public static void main (String[] args)
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
insertAndPrint(map);
}
}

Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:

1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:

-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table

Real Life Applications


Suppose you were creating a mapping of names to Person objects. You might want to
periodically output the people in alphabetical order by name. A TreeMap lets you do
this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could
be useful for a �More�function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the
ordering of insertion. This might be useful in a caching situation, when you want
to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you
need to get the keys back in insertion order, then use LinkedHashMap. If you need
to get the keys back in their true/natural order, then use TreeMap. Otherwise,
HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and
would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Recommended Posts:
HashMap and TreeMap in Java
Program to Convert HashMap to TreeMap in Java
Differences between HashMap and HashTable in Java
LinkedHashMap in Java
LinkedHashMap and LinkedHashSet in Java
LinkedHashMap get() Method in Java
LinkedHashMap removeEldestEntry() Method in Java
LinkedHashMap containsKey() Method in Java
LinkedHashMap clear() Method in Java
Print characters and their frequencies in order of occurrence using a LinkedHashMap
in Java
Java.util.TreeMap.containskey() and containsValue() in Java
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap.firstEntry() and firstKey() in Java
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Java.util.TreeMap.floorEntry() and floorKey() in Java
Article Tags :
Difference Between
Java
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Practice Tags :
Java

thumb_up
10

3.5

Based on 14 vote(s)
Feedback/ Suggest ImprovementAdd NotesImprove Article
Please write to us at contribute@geeksforgeeks.org to report any issue with the
above content.
Post navigation
Previous
first_page Java.net.HttpCookie in Java
Next
last_pageFlow control in try catch finally in Java

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments

auto

Most popular in Difference Between


Difference between Compiler and Assembler
Difference between ServletConfig and ServletContext in Java Servlet
Linux vs Unix
Difference between Use Case and Test Case
Difference between Loading and Linking

Most visited in Java


Path isAbsolute() method in Java with Examples
Buffer limit() methods in Java with Examples
ByteBuffer reset() methods in Java with Examples
ByteBuffer rewind() methods in Java with Examples
Path getFileName() method in Java with Examples

?
Write a Testimonial
?
GeeksforGeeksLinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
Algoritmi Fundamentali In Java. Aplicatii DOINA LOGOFATU

Aproximativ 783 rezultate (0,30 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
Algoritmi Fundamentali In Java. Aplicatii - Doina Logofatu
https://carturesti.ro � carte � algoritmi-fundamentali-in-java-aplicatii-55423
Algoritmi fundamentali in Java. Aplicatii prezinta riguros si atractiv tehnicile de
programare de baza (recursivitate, backtracking, programare dinamica etc.) ...
Doina Logofatu - Algoritmi fundamentali in Java: aplicatii ...
https://www.librariaeminescu.ro � isbn � Doina-Logofatu__Algoritmi-fund...
Cartea Algoritmi fundamentali in Java: aplicatii scrisa de Doina Logofatupoate fi
cumparata la pretul de 34.95 lei. Cartea a aparut la editura POLIROM. Aceasta ...
Algoritmi fundamentali in Java. Aplicatii de Doina Logofatu ...
www.piticipecreier.ro � POLIROM � informatica
autor Doina Logofatu | editura Polirom | 2007 | 372 pagini | 978-973-46-0815-7.
Algoritmi fundamentali in Java. Aplicatii Prezentare: Java este un limbaj de ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.anticariat-unu.ro � algoritmi-fundamentali-in-java-aplicatii-de-...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA LOGOFATU , 2007. Cod:
UNU103273. 10.00 Lei. STOC EPUIZAT. anunta-ma cand este disponibil ...
Algoritmi fundamentali in Java. Aplicatii - Doina Logofatu, - 34 ...
https://www.librariaonline.ro � ... � Software � Limbaje de programare
Algoritmi fundamentali in Java. Aplicatii - autor Doina Logofatu - editura - Java
este un limbaj de programare orientat-obiect dinamic si actual, folosit
frecvent ...
Carti doina logofatu - Karte.ro
www.karte.ro � carti � autor � doina-logofatu
Aplicatii. Stoc anticariat ce trebuie reconfirmat. Adauga in cos. Doina Logofatu.
Algoritmi fundamentali in Java. Aplicatii. Editura: Polirom. Anul aparitiei: 2007.
Doina Logofatu - Algoritmi fundamentali in Java - Targul Cartii
https://www.targulcartii.ro � doina-logofatu � algoritmi-fundamentali-in-ja...
Algoritmi fundamentali in Java - Doina Logofatu, editura Polirom, anul 2007. ...
Algoritmi fundamentali in Java. Aplicatii Doina Logofatu. STOC EPUIZAT!
Algoritmi fundamentali �n Java: aplicatii - Doina Logofatu ...
https://books.google.com � books � about � Algo... - Traducerea acestei pagini
Algoritmi fundamentali �n Java: aplicatii. Front Cover. Doina Logofatu. Polirom,
2007 - 370 pages. 0 Reviews. What people are saying - Write a review.
Grundlegende Algorithmen mit Java
www.algorithmen-und-problemloesungen.de � GAJ � romBuecher
Doina Logofatu, rum�nische B�cher ... Aplicatii Algoritmi fundamentali in C++. ...
Cuprins: Cuvant inainte � Algoritmi � fundamente � Introducere in POO � Java ...
ALGORITMI FUNDAMENTALI IN JAVA , APLICATII de DOINA ...
https://www.okazii.ro � Librarie � Carti � Carti stiinta � Alte carti de stiinta
26 oct. 2011 - Informatii despre ALGORITMI FULinkuri de accesibilitate
Trece?i la con?inutul principalAjutor pentru accesibilitate
Feedback privind accesibilitatea
Google
STRUCTURI DE DATE JAVA

Pagina 3 din aproximativ 168.000 rezultate (0,29 secunde)


Un memento privind confiden?ialitatea de la Google
Rezultate Cautare
Rezultate de pe web
[PDF]Coada cu prioritati
www.cs.ubbcluj.ro � ~gabitr � Cursul10-11
O astfel de structura de date se nume?te o coada cu prioritati. Folosirea cozilor
cu prioritati este similara cu utilizarea cozilor FIFO (?terge cea mai veche) ?
i ...
Mitchell Waite - Structuri de date si algoritmi in Java - 615297 ...
https://www.okazii.ro � Librarie � Carti � Carti tehnica � Carti constructii
Informatii despre Mitchell Waite - Structuri de date si algoritmi in Java - 615297.
Stoc epuizat la 21-07-2016, pret 20,99 Lei pe Okazii.ro.
[PDF]ALGORITMI SI STRUCTURI DE DATE Note de curs - FMI ...
https://fmidragos.files.wordpress.com � 2012/07 � algoritmi-si-structuri-de-d...
Cursul de Algoritmi si structuri de date este util (si chiar necesar) pentru ...
necesare pentru acest curs dar ecesta nu este un curs de programare in Java.
Stefan-Gheorghe Pentiuc - Java. Structuri de date si algoritmi ...
https://www.librariaeminescu.ro � isbn � Stefan-Gheorghe-Pentiuc__Java-S...
Cartea Java. Structuri de date si algoritmi scrisa de Stefan-Gheorghe Pentiucpoate
fi cumparata la pretul de 36.99 lei. Cartea a aparut la editura MATRIX ROM.
Arta progamarii in Java. Algoritmi si structuri de date - Daniel ...
https://www.libris.ro � arta-progamarii-in-java-algoritmi-si-structuri-de-alb...
Arta programarii in JAVA Algoritmi si Structuri de Date, materializeaza dorinta
autorilor ei de a prezenta in fata cititorilor, avizati sau in curs de
initiere, ...
[PDF]8. Arbori - UPT
staff.cs.upt.ro � teaching � upt � id21-aa � lectures � AA-ID-Cap08-1
La fel ca si �n cazul altor tipuri de structuri de date, este dificil de stabilit
un set de ... Aceste tehnici �si au sorgintea �n traversarea structurilor de date
graf, dar prin.
[PDF]Structuri de date de tip stiva si coada Breviar teoretic
robotics.ucv.ro � carti � java � lab5 � LAB5
5 - Structuri de date de tip stiva si coada ... Concluzionand, putem defini Stiva
drept o structura de date abstracta pentru care atat operatia de ... import
java.io.*;.
[PDF]Cozi si stive
ase.softmentor.ro � StructuriDeDate � Fisiere � 05_CoziStive
Cozile si stivele sunt structuri de date logice (implementarea este facuta ...
Ambele structuri au doua operatii de baza: adaugarea si extragerea unui element.
�n.
Structuri De Date - OLX.ro
https://www.olx.ro � oferte � q-structuri-de-date
Structuri De Date OLX.ro. ... Cablare structurata,configurare routere,realizare
retele date si voce. Servicii, afaceri ... Structuri de date si algoritmi in
JAVA ...
Java. structuri de date si algoritmi de Stefan Gheorghe Pentiuc ...
https://serialreaders.com � detalii-carte � 1666-java-structuri-de-date-si-alg...
Java. structuri de date si algoritmi. scrisa de Stefan Gheorghe Pentiuc Java.
structuri de date si algoritmi de Stefan Gheorghe Pentiuc Propune aceasta ...
Cautari referitoare la STRUCTURI DE DATE JAVA
structuri de date si algoritmi

structuri de date c++

structuri de date probleme rezolvate

structuri de date neomogene

structuri de date ase

structuri de date pbinfo

Navigare �n pagini
�napoi
1
2
3
4
5
6
7
8
9
10
�nainte
Linkuri din subsol
Rom�niaCalea Sever Bocu, Timi?oara - Dupa adresa de internet - Utiliza?i loca?ia
exacta - Afla?i mai multe
AjutorTrimite?i feedbackConfi

Вам также может понравиться