Este documento é um manual de referência gerado pelo Doxygen para documentar classes e métodos. Ele contém a descrição de 11 classes relacionadas a algoritmos de ordenação, incluindo BubbleSort, InsertionSort, QuickSort e outras, com detalhes sobre seus construtores, métodos e membros.
11. 8
4.1.1
Class Documentation
Detailed Description
Classe base para uso do padrão strategy.
Definition at line 17 of file SortingAlgorithms.h.
4.1.2
Constructor & Destructor Documentation
4.1.2.1
AbstractSorting::AbstractSorting ()
Constructor
Definition at line 16 of file SortingAlgorithms.cxx.
00017 {
00018
InitializeVariables();
00019 }
Here is the call graph for this function:
AbstractSorting::AbstractSorting
4.1.2.2
AbstractSorting::InitializeVariables
virtual AbstractSorting::∼AbstractSorting () [inline, virtual]
Método destrutor. Responsável por liberar todos os recursos alocados.
Definition at line 78 of file SortingAlgorithms.h.
00078 {}
4.1.3
Member Function Documentation
4.1.3.1
long double AbstractSorting::ComparisonsNumber (void) [inline]
Método que retorna o número de comparações realizadas entre elementos da lista de Elementos.
Definition at line 68 of file SortingAlgorithms.h.
00068 { return _numero_de_comparacoes; };
Here is the caller graph for this function:
AbstractSorting::ComparisonsNumber
4.1.3.2
main
void AbstractSorting::InitializeVariables (void)
Método que executa a inicialização das variáveis de estado da classe para posterior avaliação do desempenho dos algoritmos utilizados.
Definition at line 26 of file SortingAlgorithms.cxx.
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
12. 4.1 AbstractSorting Class Reference
9
00027 {
00028
_numero_de_iteracoes
= 0;
00029
_numero_de_trocas
= 0;
00030
_numero_de_comparacoes = 0;
00031 }
Here is the caller graph for this function:
AbstractSorting::InitializeVariables
4.1.3.3
AbstractSorting::AbstractSorting
long double AbstractSorting::InversionsNumber (void) [inline]
Método que retorna o número de trocas ou mudanças de valor entre posições dentro da lista de Elementos.
Definition at line 62 of file SortingAlgorithms.h.
00062 { return _numero_de_trocas; };
Here is the caller graph for this function:
AbstractSorting::InversionsNumber
4.1.3.4
main
long double AbstractSorting::IterationsNumber (void) [inline]
Método que retorna o número de iterações realizadas pelo último algoritmo de ordenação executado.
Definition at line 56 of file SortingAlgorithms.h.
00056 { return _numero_de_iteracoes; };
Here is the caller graph for this function:
AbstractSorting::IterationsNumber
4.1.3.5
main
virtual void AbstractSorting::sort (ElementVector & ev) [pure virtual]
Método que executa a ordenação dos elementos.
Implemented in BubbleSort, BubbleSort2, GnomeSort, ShakerSort, CombSort, InsertionSort, SelectionSort, QuickPivotCentral, QuickPivotPeripheral, MergeSort, ShellSort, HeapSort, and InternalQuickSort.
Here is the caller graph for this function:
AbstractSorting::sort
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
ExecuteSort
main
13. 10
Class Documentation
4.1.4
Member Data Documentation
4.1.4.1
long double AbstractSorting::_numero_de_comparacoes [protected]
Atributo que irá armazenar o número de comparações realizadas.
Definition at line 37 of file SortingAlgorithms.h.
4.1.4.2
long double AbstractSorting::_numero_de_iteracoes [protected]
Atributo que irá armazenar o numero de iterações realizadas em cada algoritmo contado como operação de
maior relevância a comparação e a possivel troca de valor entre duas posições que armazenam o valor de
um determinado elemento.
Definition at line 26 of file SortingAlgorithms.h.
4.1.4.3
long double AbstractSorting::_numero_de_trocas [protected]
Atributo que irá armazenar para alguns algoritmos o número efetivo de trocas realizadas necessárias para a
ordenação da lista de elementos
Definition at line 32 of file SortingAlgorithms.h.
The documentation for this class was generated from the following files:
• SortingAlgorithms.h
• SortingAlgorithms.cxx
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
14. 4.2 BubbleSort Class Reference
4.2
11
BubbleSort Class Reference
#include <SortingAlgorithms.h>
Inheritance diagram for BubbleSort:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
BubbleSort
+ BubbleSort()
+ sort()
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
15. 12
Class Documentation
Collaboration diagram for BubbleSort:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
BubbleSort
+ BubbleSort()
+ sort()
Public Member Functions
• BubbleSort ()
• void sort (ElementVector &ev)
4.2.1
Detailed Description
Método da ordenação em bolha ou método bubble sort. Esse primeiro método é da ordem quadrática e não
constitui um algoritmo ótimo para ordenação, porém sua complexidade de implementação é muita baixa
(trivial) em relação a outros algoritmos da mesma classe tal como o quicksort.
Definition at line 88 of file SortingAlgorithms.h.
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
16. 4.2 BubbleSort Class Reference
13
4.2.2
Constructor & Destructor Documentation
4.2.2.1
BubbleSort::BubbleSort () [inline]
Contructor
Definition at line 94 of file SortingAlgorithms.h.
00094 :AbstractSorting(){};
4.2.3
Member Function Documentation
4.2.3.1
void BubbleSort::sort (ElementVector & ev) [virtual]
Método que executa a ordenação dos elementos.
Método da ordenação em bolha ou bubblesort. Esse primeiro método é da ordem quadrática e não constitui
um algoritmo ótimo para ordenação, porém sua complexidade de implementação é muita baixa (trivial) em
relação a outros algoritmos da mesma classe tal como o quicksort.
Implements AbstractSorting.
Definition at line 43 of file SortingAlgorithms.cxx.
00044 {
00045
//std::cout << "Bubble..." << std::endl;
00046
register unsigned int i,j;
00047
00048
//executa loopings para varrer a lista de números
00049
for (i = 1; i < ev.size(); ++i)
00050
{
00051
for(j = ev.size()-1; j >= i; --j)
00052
{
00053
//executa troca caso encontre elementos desordenados
00054
if ( ev[j-1] > ev[j] )
00055
{
00056
ev.swap(j-1,j);
00057
_numero_de_trocas++;
00058
}
00059
_numero_de_comparacoes++;
00060
_numero_de_iteracoes++;
00061
}
00062
}
00063 }
Here is the call graph for this function:
ElementVector::size
BubbleSort::sort
ElementVector::swap
The documentation for this class was generated from the following files:
• SortingAlgorithms.h
• SortingAlgorithms.cxx
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
17. 14
4.3
Class Documentation
BubbleSort2 Class Reference
#include <SortingAlgorithms.h>
Inheritance diagram for BubbleSort2:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
BubbleSort2
+ BubbleSort2()
+ sort()
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
18. 4.3 BubbleSort2 Class Reference
15
Collaboration diagram for BubbleSort2:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
BubbleSort2
+ BubbleSort2()
+ sort()
Public Member Functions
• BubbleSort2 ()
• void sort (ElementVector &ev)
4.3.1
Detailed Description
Método da ordenação em bolha com alguma melhora em relação ao número de iterações e trocas. Caso
não haja nenhuma troca o algoritmo não executa todas as iterações necessarias. Caso hajam muitas trocas
a serem feitas o número de iterações irá superar o convencional estipulado pelo algoritmo BubbleSort
convencional.
Definition at line 109 of file SortingAlgorithms.h.
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
19. 16
Class Documentation
4.3.2
Constructor & Destructor Documentation
4.3.2.1
BubbleSort2::BubbleSort2 () [inline]
Contructor
Definition at line 115 of file SortingAlgorithms.h.
00115 :AbstractSorting(){};
4.3.3
Member Function Documentation
4.3.3.1
void BubbleSort2::sort (ElementVector & ev) [virtual]
Método que executa a ordenação dos elementos.
Método da ordenação em bolha com alguma melhora em relação ao número de iterações e trocas. Caso
não haja nenhuma troca o algoritmo não executa todas as iterações necessarias. Caso hajam muitas trocas
a serem feitas o número de iterações irá superar o convencional estipulado pelo algoritmo BubbleSort
convencional.
Implements AbstractSorting.
Definition at line 72 of file SortingAlgorithms.cxx.
00073 {
00074
bool houvetroca = false;
00075
register unsigned int index = 0;
00076
register unsigned int size_vector = ev.size();
00077
00078
while ((!houvetroca) && (index < size_vector - 1))
00079
{
00080
index = 0;
00081
while(index < size_vector - 1)
00082
{
00083
00084
//Verifica o número de comparações realizadas
00085
_numero_de_comparacoes++;
00086
00087
//Verifica se algum elemento deve sofrer inversão
00088
if (ev[index] > ev[index + 1])
00089
{
00090
ev.swap(index + 1,index);
00091
houvetroca = true;
00092
_numero_de_trocas++;
00093
}
00094
00095
//Caso haja troca retorna o indice para o começo da lista
00096
if(houvetroca) { index = 0; houvetroca = false; }
00097
else { ++index;}
00098
_numero_de_iteracoes++;
00099
}
00100
}
00101 }
Here is the call graph for this function:
ElementVector::size
BubbleSort2::sort
ElementVector::swap
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
20. 4.3 BubbleSort2 Class Reference
The documentation for this class was generated from the following files:
• SortingAlgorithms.h
• SortingAlgorithms.cxx
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
17
21. 18
4.4
Class Documentation
CombSort Class Reference
#include <SortingAlgorithms.h>
Inheritance diagram for CombSort:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
CombSort
+ CombSort()
+ sort()
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
22. 4.4 CombSort Class Reference
19
Collaboration diagram for CombSort:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
CombSort
+ CombSort()
+ sort()
Public Member Functions
• CombSort ()
• void sort (ElementVector &ev)
4.4.1
Detailed Description
Método que repetidamente reordena diferentes pares de itens, separados por um salto, que é calculado a
cada passagem, semelhante ao Bubble Sort, porém mais eficiente. O CombSort é um algoritmo relativamente simplista orinalmente criado por Wlodek Dobosiewicz em 1980, mais tarde redescoberto e popularizado por Stephen Lacey e Richard Box com um artigo na Byte Magazine [artigo publicado em abril
em 1991]. A idéia básica é a eliminação das ’Turtles’, ou valores pequenos perto do final da lista, já que
no bubble sort estes valores pequenos retardam tremendamente a triagem e ordenação quando deslocados
para baixo[ou começo da lista]. ’Rabbits’, grandes valores em torno do início da lista, não representam um
problema no bubble sort. A maioria dos autores interpretam esse algoritmo como uma variante do Shell
Sort, só que usando um núcleo baseado em trocas [bubble] ao invés de inserções como o próprio Shell Sort.
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
23. 20
Class Documentation
Definition at line 180 of file SortingAlgorithms.h.
4.4.2
Constructor & Destructor Documentation
4.4.2.1
CombSort::CombSort () [inline]
Contructor
Definition at line 186 of file SortingAlgorithms.h.
00186 :AbstractSorting(){};
4.4.3
Member Function Documentation
4.4.3.1
void CombSort::sort (ElementVector & ev) [virtual]
Método que executa a ordenação dos elementos.
Método que repetidamente reordena diferentes pares de itens, separados por um salto, que é calculado a
cada passagem, semelhante ao Bubble Sort, porém mais eficiente. O CombSort é um algoritmo relativamente simplista orinalmente criado por Wlodek Dobosiewicz em 1980, mais tarde redescoberto e popularizado por Stephen Lacey e Richard Box com um artigo na Byte Magazine [artigo publicado em abril
em 1991]. A idéia básica é a eliminação das ’Turtles’, ou valores pequenos perto do final da lista, já que
no bubble sort estes valores pequenos retardam tremendamente a triagem e ordenação quando deslocados
para baixo[ou começo da lista]. ’Rabbits’, grandes valores em torno do início da lista, não representam um
problema no bubble sort. A maioria dos autores interpretam esse algoritmo como uma variante do Shell
Sort, só que usando um núcleo baseado em trocas [bubble] ao invés de inserções como o próprio Shell Sort.
Implements AbstractSorting.
Definition at line 556 of file SortingAlgorithms.cxx.
00557 {
00558
//Variáveis de controle do tamanho do gap/salto/intervalo e troca de elementos
00559
int gap = (int)ev.size();
00560
int size_vector = (int)ev.size();
00561
bool swapped = true;
00562
00563
//Verifica se o gap é maior que um ou se ainda está ocorrendo trocas
00564
while (gap > 1 || swapped)
00565
{
00566
//Calculo do gap/salto/intervalo de aferição ou comparação dos elementos
00567
if (gap > 1) { gap = (int) (gap / 1.3); }
00568
00569
//Variaveis de controle
00570
int i = 0;
00571
swapped = false;
00572
00573
//Looping onde ocorrerá verificações e trocas
00574
while (i + gap < size_vector)
00575
{
00576
_numero_de_iteracoes++;
00577
_numero_de_comparacoes++;
00578
if (ev[i] > ev[i + gap])
00579
{
00580
_numero_de_trocas++;
00581
ev.swap(i, i+gap);
00582
swapped = true;
00583
}
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
24. 4.4 CombSort Class Reference
21
00584
i++;
00585
}
00586
}
00587 }
Here is the call graph for this function:
ElementVector::size
CombSort::sort
ElementVector::swap
The documentation for this class was generated from the following files:
• SortingAlgorithms.h
• SortingAlgorithms.cxx
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
25. 22
Class Documentation
4.5
Element Class Reference
#include <Element.h>
Public Member Functions
•
•
•
•
•
•
•
Element (long double value=0.0)
void value (long double Value)
long double value (void)
bool operator> (Element &e)
bool operator< (Element &e)
bool operator<= (Element &e)
virtual ∼Element ()
4.5.1
Detailed Description
Classe para armazenamento das caracteristicas de um determinado elemento
Definition at line 18 of file Element.h.
4.5.2
Constructor & Destructor Documentation
4.5.2.1
Element::Element (long double value = 0.0) [inline]
Método construtor da classe.
Definition at line 30 of file Element.h.
00030 {_value = value;};
Here is the call graph for this function:
Element::Element
4.5.2.2
Element::value
virtual Element::∼Element () [inline, virtual]
Método destrutor. Responsável por liberar todos os recursos alocados pela classe.
Definition at line 61 of file Element.h.
00061 {};
4.5.3
Member Function Documentation
4.5.3.1
bool Element::operator< (Element & e) [inline]
Sobrecarga do operador < para simplificação da comparação de valores.
Definition at line 50 of file Element.h.
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
26. 4.5 Element Class Reference
23
00050 { return (this->value() < e.value()); };
Here is the call graph for this function:
Element::operator<
4.5.3.2
Element::value
bool Element::operator<= (Element & e) [inline]
Sobrecarga do operador <= para simplificação da comparação de valores.
Definition at line 55 of file Element.h.
00055 { return (this->value() <= e.value()); };
Here is the call graph for this function:
Element::operator<=
4.5.3.3
Element::value
bool Element::operator> (Element & e) [inline]
Sobrecarga do operador > para simplificação da comparação de valores.
Definition at line 45 of file Element.h.
00045 { return (this->value() > e.value()); };
Here is the call graph for this function:
Element::operator>
4.5.3.4
Element::value
long double Element::value (void) [inline]
Método que retorna o valor contido no atributo value.
Definition at line 40 of file Element.h.
00040 { return _value; };
Here is the caller graph for this function:
Element::Element
Element::operator<
Element::value
Element::operator<=
Element::operator>
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
27. 24
Class Documentation
4.5.3.5
void Element::value (long double Value) [inline]
Método que atribui um valor ao atributo value.
Definition at line 35 of file Element.h.
00035 { _value = Value; };
Here is the caller graph for this function:
main
ElementVector::maxValue
ElementVector::absMaxValue
ElementVector::minValue
Element::value
Element::operator<
Element::operator<=
Element::operator>
The documentation for this class was generated from the following file:
• Element.h
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
28. 4.6 ElementVector Class Reference
4.6
25
ElementVector Class Reference
#include <Element.h>
Public Member Functions
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
ElementVector (void)
long double maxValue (void)
long double minValue (void)
long double absMaxValue (void)
bool isEmpty (void)
void resize (unsigned int new_size)
void sort (void)
unsigned int size (void)
Element at (unsigned int index)
Element & operator[ ] (unsigned int index)
void push_back (Element e)
void add (Element e)
void swap (unsigned int position_a, unsigned int position_b)
void clear (void)
virtual ∼ElementVector ()
4.6.1
Detailed Description
Classe para armazenamento de uma lista de elementos
Definition at line 76 of file Element.h.
4.6.2
Constructor & Destructor Documentation
4.6.2.1
ElementVector::ElementVector (void) [inline]
Método construtor da classe.
Definition at line 88 of file Element.h.
00088 {};
4.6.2.2
virtual ElementVector::∼ElementVector () [inline, virtual]
Método destrutor. Responsável por liberar todos os recursos alocados pela classe.
Definition at line 163 of file Element.h.
00163 { clear(); }
Here is the call graph for this function:
ElementVector::~ElementVector
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
ElementVector::clear
29. 26
Class Documentation
4.6.3
Member Function Documentation
4.6.3.1
long double ElementVector::absMaxValue (void)
Método que retorna o maior valor absoluto contido na lista.
Definition at line 54 of file Element.cxx.
00055 {
00056
return (fabsl(maxValue()) > fabsl(minValue()))?(maxValue()):(fabsl(minValue()))
;
00057 }
Here is the call graph for this function:
ElementVector::maxValue
ElementVector::at
ElementVector::minValue
Element::value
ElementVector::absMaxValue
4.6.3.2
void ElementVector::add (Element e) [inline]
Método que insere elementos na lista
Definition at line 146 of file Element.h.
00146 { this->push_back(e);
}
Here is the call graph for this function:
ElementVector::add
ElementVector::push_back
Here is the caller graph for this function:
ElementVector::add
4.6.3.3
main
Element ElementVector::at (unsigned int index) [inline]
Método que retorna o elemento de uma determinada posição
Definition at line 128 of file Element.h.
00128 { return _list.at(index); };
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
30. 4.6 ElementVector Class Reference
27
Here is the caller graph for this function:
main
ElementVector::at
ElementVector::maxValue
ElementVector::absMaxValue
ElementVector::minValue
4.6.3.4
void ElementVector::clear (void) [inline]
Método que executa limpeza da lista de elementos
Definition at line 157 of file Element.h.
00157 { _list.clear(); }
Here is the caller graph for this function:
MergeSort::Merges
MergeSort::MergeMethod
MergeSort::sort
ElementVector::clear
ElementVector::~ElementVector
4.6.3.5
bool ElementVector::isEmpty (void) [inline]
Método que verifica se a alista está vazia
Definition at line 108 of file Element.h.
00108 { return _list.empty(); };
4.6.3.6
long double ElementVector::maxValue (void)
Método que retorna o maior valor existente na lista de elementos
Definition at line 13 of file Element.cxx.
00014 {
00015
//Verificando se a lista foi preenchida ...
00016
if (_list.size() == 0 ) return 0;
00017
00018
//Resgatando o primeiro elemento da lista para verificação do maior elemento
00019
long double maximo = at(0).value();
00020
00021
//Looping para verificação do maior elemento
00022
for (unsigned int index = 1; index < _list.size(); index++)
00023
{
00024
if (maximo < at(index).value()) maximo = at(index).value();
00025
}
00026
00027
//Retornando o maior valor da lista
00028
return maximo;
00029 }
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
31. 28
Class Documentation
Here is the call graph for this function:
ElementVector::at
ElementVector::maxValue
Element::value
Here is the caller graph for this function:
ElementVector::maxValue
4.6.3.7
ElementVector::absMaxValue
long double ElementVector::minValue (void)
Método que retorna o menor valor existente na lista de elementos
Definition at line 33 of file Element.cxx.
00034 {
00035
//Verificando se a lista foi preenchida ...
00036
if (_list.size() == 0 ) return 0;
00037
00038
//Resgatando o primeiro elemento da lista para verificação do maior elemento
00039
long double minimo = at(0).value();
00040
00041
//Looping para verificação do maior elemento
00042
for (unsigned int index = 1; index < _list.size(); index++)
00043
{
00044
if (minimo > at(index).value()) minimo = at(index).value();
00045
}
00046
00047
//Retornando o maior valor da lista
00048
return minimo;
00049 }
Here is the call graph for this function:
ElementVector::at
ElementVector::minValue
Element::value
Here is the caller graph for this function:
ElementVector::minValue
4.6.3.8
ElementVector::absMaxValue
Element& ElementVector::operator[ ] (unsigned int index) [inline]
Sobrecarga do operador [] para simplificar o acesso a um determinado elemento. Lembrando que esse
operador devolve uma referência, o que faz que acessemos diretamente o valor do objeto, além disso não
executamos verificação de limites com esse operador, isso fica a cargo do programador.
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
32. 4.6 ElementVector Class Reference
29
Definition at line 136 of file Element.h.
00136 { return _list[index]; };
4.6.3.9
void ElementVector::push_back (Element e) [inline]
Método que insere elementos na lista
Definition at line 141 of file Element.h.
00141 { _list.push_back(e); }
Here is the caller graph for this function:
ElementVector::push_back
4.6.3.10
ElementVector::add
main
void ElementVector::resize (unsigned int new_size) [inline]
Método que executa um resize na lista de elementos
Definition at line 113 of file Element.h.
00113 { _list.resize(new_size); };
Here is the caller graph for this function:
ElementVector::resize
4.6.3.11
MergeSort::Merges
MergeSort::MergeMethod
unsigned int ElementVector::size (void) [inline]
Método que retorna o tamanho da lista de elementos
Definition at line 123 of file Element.h.
00123 { return _list.size(); }
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
MergeSort::sort
33. 30
Class Documentation
Here is the caller graph for this function:
main
CombSort::sort
ShakerSort::sort
GnomeSort::sort
HeapSort::sort
ShellSort::sort
ElementVector::size
MergeSort::sort
QuickPivotPeripheral::sort
QuickPivotCentral::sort
SelectionSort::sort
InsertionSort::sort
BubbleSort2::sort
BubbleSort::sort
4.6.3.12
void ElementVector::sort (void) [inline]
Método que utiliza o algoritmo de ordenação quick sort fornecido pela STL
Definition at line 118 of file Element.h.
00118 { std::sort(_list.begin(), _list.end(), PredicateSort()); };
Here is the caller graph for this function:
ElementVector::sort
4.6.3.13
InternalQuickSort::sort
void ElementVector::swap (unsigned int position_a, unsigned int position_b)
Método que executa a troca entre dois valores de uma determinada posição dentro da lista de elementos.
Definition at line 63 of file Element.cxx.
00064 {
00065
//Executa a troca dos valores
00066
long double temp = _list[position_a].value();
00067
_list[position_a].value( _list[position_b].value() );
00068
_list[position_b].value(temp);
00069 }
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
34. 4.6 ElementVector Class Reference
31
Here is the caller graph for this function:
QuickPivotPeripheral::Partition
QuickPivotPeripheral::QSort
CombSort::sort
ShakerSort::sort
ElementVector::swap
GnomeSort::sort
SelectionSort::sort
BubbleSort2::sort
BubbleSort::sort
The documentation for this class was generated from the following files:
• Element.h
• Element.cxx
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
QuickPivotPeripheral::sort
35. 32
4.7
Class Documentation
GnomeSort Class Reference
#include <SortingAlgorithms.h>
Inheritance diagram for GnomeSort:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
GnomeSort
+ GnomeSort()
+ sort()
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
36. 4.7 GnomeSort Class Reference
33
Collaboration diagram for GnomeSort:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
GnomeSort
+ GnomeSort()
+ sort()
Public Member Functions
• GnomeSort ()
• void sort (ElementVector &ev)
4.7.1
Detailed Description
Método similiar ao Insertion sort com a diferença que o GnomeSort leva um elemento para sua posição
correta, com uma seqüencia grande de trocas assim como o Bubble sort. O algoritmo percorre o vetor
comparando seus elementos dois a dois, assim que ele encontra um elemento que está na posição incorreta,
ou seja, um número maior antes de um menor, ele troca a posição dos elementos, e volta com este elemento
até que encontre o seu respectivo lugar.
Definition at line 132 of file SortingAlgorithms.h.
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
37. 34
Class Documentation
4.7.2
Constructor & Destructor Documentation
4.7.2.1
GnomeSort::GnomeSort () [inline]
Contructor
Definition at line 138 of file SortingAlgorithms.h.
00138 :AbstractSorting(){};
4.7.3
Member Function Documentation
4.7.3.1
void GnomeSort::sort (ElementVector & ev) [virtual]
Método que executa a ordenação dos elementos.
Método similiar ao Insertion sort com a diferença que o GnomeSort leva um elemento para sua posição
correta, com uma seqüencia grande de trocas assim como o Bubble sort. O algoritmo percorre o vetor
comparando seus elementos dois a dois, assim que ele encontra um elemento que está na posição incorreta,
ou seja, um número maior antes de um menor, ele troca a posição dos elementos, e volta com este elemento
até que encontre o seu respectivo lugar.
Implements AbstractSorting.
Definition at line 463 of file SortingAlgorithms.cxx.
00464 {
00465
//Controlador de indice de posicionamento
00466
unsigned int index = 1;
00467
00468
//looping que executa as ordenações
00469
while( index < ev.size() )
00470
{
00471
//Sempre executa uma comparação antes de modificar o índice
00472
_numero_de_comparacoes++;
00473
_numero_de_iteracoes++;
00474
if((index == 0) || ( ev[index-1] <= ev[index] ))
00475
{
00476
index++;
00477
}
00478
else
00479
{
00480
_numero_de_trocas++;
00481
ev.swap( index - 1, index );
00482
--index;
00483
}
00484
}
00485 }
Here is the call graph for this function:
ElementVector::size
GnomeSort::sort
ElementVector::swap
The documentation for this class was generated from the following files:
• SortingAlgorithms.h
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
38. 4.7 GnomeSort Class Reference
• SortingAlgorithms.cxx
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
35
39. 36
4.8
Class Documentation
HeapSort Class Reference
#include <SortingAlgorithms.h>
Inheritance diagram for HeapSort:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
HeapSort
+ HeapSort()
+ sort()
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
40. 4.8 HeapSort Class Reference
37
Collaboration diagram for HeapSort:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
HeapSort
+ HeapSort()
+ sort()
Public Member Functions
• HeapSort ()
• void sort (ElementVector &ev)
4.8.1
Detailed Description
O algoritmo heapsort é um algoritmo de ordenação generalista, e faz parte da família de algoritmos de
ordenação por seleção. Tem um desempenho em tempo de execução muito bom em conjuntos ordenados
aleatoriamente, tem um uso de memória bem comportado e o seu desempenho em pior cenário é praticamente igual ao desempenho em cenário médio. Alguns algoritmos de ordenação rápidos têm desempenhos
espectacularmente ruins no pior cenário, quer em tempo de execução, quer no uso da memória. O Heapsort
trabalha no lugar e o tempo de execução em pior cenário para ordenar n elementos é de O (n lg n). Para
valores de n, razoavelmente grande, o termo lg n é quase constante, de modo que o tempo de ordenação é
quase linear com o número de itens a ordenar.
Definition at line 367 of file SortingAlgorithms.h.
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
41. 38
Class Documentation
4.8.2
Constructor & Destructor Documentation
4.8.2.1
HeapSort::HeapSort () [inline]
Contructor
Definition at line 373 of file SortingAlgorithms.h.
00373 :AbstractSorting(){};
4.8.3
Member Function Documentation
4.8.3.1
void HeapSort::sort (ElementVector & ev) [virtual]
Método que executa a ordenação dos elementos.
O algoritmo heapsort é um algoritmo de ordenação generalista, e faz parte da família de algoritmos de
ordenação por seleção. Tem um desempenho em tempo de execução muito bom em conjuntos ordenados
aleatoriamente, tem um uso de memória bem comportado e o seu desempenho em pior cenário é praticamente igual ao desempenho em cenário médio. Alguns algoritmos de ordenação rápidos têm desempenhos
espectacularmente ruins no pior cenário, quer em tempo de execução, quer no uso da memória. O Heapsort
trabalha no lugar e o tempo de execução em pior cenário para ordenar n elementos é de O (n lg n). Para
valores de n, razoavelmente grande, o termo lg n é quase constante, de modo que o tempo de ordenação é
quase linear com o número de itens a ordenar.
Implements AbstractSorting.
Definition at line 393 of file SortingAlgorithms.cxx.
00394 {
00395
int i = ev.size()/2, n = ev.size(), pai, filho;
00396
Element t;
00397
00398
for (;;)
00399
{
00400
if (i > 0)
00401
{
00402
i--;
00403
t = ev[i];
00404
}
00405
else
00406
{
00407
n--;
00408
if (n == 0) return;
00409
t = ev[n];
00410
ev[n] = ev[0];
00411
}
00412
00413
pai = i;
00414
filho = i*2 + 1;
00415
00416
while (filho < n)
00417
{
00418
if ((filho + 1 < n) && (ev[filho + 1] > ev[filho]))
00419
{
00420
filho++;
00421
_numero_de_comparacoes++;
00422
}
00423
00424
if (ev[filho] > t)
00425
{
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
42. 4.8 HeapSort Class Reference
00426
00427
00428
00429
00430
00431
00432
00433
00434
00435
00436
00437
00438
00439
00440
00441
}
00442 }
39
ev[pai] = ev[filho];
pai = filho;
filho = pai*2 + 1;
_numero_de_comparacoes++;
_numero_de_trocas++;
}
else
break;
_numero_de_iteracoes++;
}
ev[pai] = t;
//_numero_de_trocas++;
_numero_de_iteracoes++;
Here is the call graph for this function:
HeapSort::sort
ElementVector::size
The documentation for this class was generated from the following files:
• SortingAlgorithms.h
• SortingAlgorithms.cxx
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
43. 40
4.9
Class Documentation
InsertionSort Class Reference
#include <SortingAlgorithms.h>
Inheritance diagram for InsertionSort:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
InsertionSort
+ InsertionSort()
+ sort()
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
44. 4.9 InsertionSort Class Reference
41
Collaboration diagram for InsertionSort:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
InsertionSort
+ InsertionSort()
+ sort()
Public Member Functions
• InsertionSort ()
• void sort (ElementVector &ev)
4.9.1
Detailed Description
Método da ordenação por inserção que também possui complexidade quadrática porém em média se comporta melhor que a ordenação pelo método bolha.
Definition at line 198 of file SortingAlgorithms.h.
4.9.2
Constructor & Destructor Documentation
4.9.2.1
InsertionSort::InsertionSort () [inline]
Contructor
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
45. 42
Class Documentation
Definition at line 204 of file SortingAlgorithms.h.
00204 :AbstractSorting(){};
4.9.3
Member Function Documentation
4.9.3.1
void InsertionSort::sort (ElementVector & ev) [virtual]
Método que executa a ordenação dos elementos.
Método da ordenação por inserção que também possui complexidade quadrática porém em média se comporta melhor que a ordenação pelo método bolha.
Implements AbstractSorting.
Definition at line 107 of file SortingAlgorithms.cxx.
00108 {
00109
Element temp;
00110
int index;
00111
unsigned int j, size_vector = ev.size();
00112
00113
for(j = 1; j < size_vector; j++)
00114
{
00115
temp = ev[j];
00116
00117
//O algoritmo faz pelo menos uma comparação antes de entrar no looping e uma
00118
//iteração pois se as condições do cabeçalho condicional do próximo laço não
00119
//forem aceitas o looping[for] não será executado.
00120
_numero_de_iteracoes++;
00121
_numero_de_comparacoes++;
00122
00123
//O restante das comparações são feitas pelo cabeçalho condicional do laço
00124
for(index = j-1; index >= 0 && ev[index] > temp; index--)
00125
{
00126
ev[index + 1] = ev[index];
00127
_numero_de_iteracoes++;
00128
_numero_de_trocas++;
00129
_numero_de_comparacoes++;
00130
}
00131
00132
//Necessáriamente isso é apenas uma reatribuição quando a lista já se
00133
//encontra ordenada, por isso comentamos o incremento do número de trocas
00134
//_numero_de_trocas++;
00135
ev[index + 1] = temp;
00136
}
00137 }
Here is the call graph for this function:
InsertionSort::sort
ElementVector::size
The documentation for this class was generated from the following files:
• SortingAlgorithms.h
• SortingAlgorithms.cxx
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
46. 4.10 InternalQuickSort Class Reference
4.10
43
InternalQuickSort Class Reference
#include <SortingAlgorithms.h>
Inheritance diagram for InternalQuickSort:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
InternalQuickSort
+ InternalQuickSort()
+ sort()
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
47. 44
Class Documentation
Collaboration diagram for InternalQuickSort:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
InternalQuickSort
+ InternalQuickSort()
+ sort()
Public Member Functions
• InternalQuickSort ()
• void sort (ElementVector &ev)
4.10.1
Detailed Description
Método que utiliza o algoritmo quiscksort implementado pela STL. Por isso o número de comparações,
iterações e trocas não poderá ser fornecido com precisão
Definition at line 385 of file SortingAlgorithms.h.
4.10.2
Constructor & Destructor Documentation
4.10.2.1
InternalQuickSort::InternalQuickSort () [inline]
Contructor
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
48. 4.10 InternalQuickSort Class Reference
45
Definition at line 391 of file SortingAlgorithms.h.
00391 :AbstractSorting(){};
4.10.3
Member Function Documentation
4.10.3.1
void InternalQuickSort::sort (ElementVector & ev) [virtual]
Método que executa a ordenação dos elementos.
Método que utiliza o algoritmo quiscksort implementado pela STL. Por isso o número de comparações,
iterações e trocas não poderá ser fornecido com precisão
Implements AbstractSorting.
Definition at line 448 of file SortingAlgorithms.cxx.
00449 {
00450
//Executa o método de ordenação fornecido pela STL baseado no quicksort
00451
ev.sort();
00452 }
Here is the call graph for this function:
InternalQuickSort::sort
ElementVector::sort
The documentation for this class was generated from the following files:
• SortingAlgorithms.h
• SortingAlgorithms.cxx
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
49. 46
4.11
Class Documentation
MergeSort Class Reference
#include <SortingAlgorithms.h>
Inheritance diagram for MergeSort:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
MergeSort
+ MergeSort()
+ sort()
+ MergeMethod()
+ Merges()
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
50. 4.11 MergeSort Class Reference
47
Collaboration diagram for MergeSort:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
MergeSort
+ MergeSort()
+ sort()
+ MergeMethod()
+ Merges()
Public Member Functions
• MergeSort ()
• void sort (ElementVector &ev)
• void MergeMethod (ElementVector &ev, int BeginList, int EndList)
• void Merges (ElementVector &ev, int BeginList, int Middle, int EndList)
4.11.1
Detailed Description
Método de Ordenação Merge Sort
Definition at line 298 of file SortingAlgorithms.h.
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
51. 48
Class Documentation
4.11.2
Constructor & Destructor Documentation
4.11.2.1
MergeSort::MergeSort () [inline]
Contructor
Definition at line 304 of file SortingAlgorithms.h.
00304 :AbstractSorting(){};
4.11.3
Member Function Documentation
4.11.3.1
void MergeSort::MergeMethod (ElementVector & ev, int BeginList, int EndList)
Método merge sort, ou ordenação por intercalação, é um exemplo de algoritmo de ordenação do tipo
dividir-para-conquistar. Sua idéia básica é que é muito fácil criar uma sequência ordenada a partir de duas
outras também ordenadas. Para isso, ele divide a sequência original em pares de dados, ordena-as; depois
as agrupa em sequências de quatro elementos, e assim por diante, até ter toda a sequência dividida em
apenas duas partes. O método MergeSort rearranja o vetor v[BeginList..EndList-1] em ordem crescente.
Cuidado ao usar esse método, o final da lista compreende todo o seu tamanho, logo o mesmo deve ser
chamado da seguinte forma : MergeSort(MinhaLista, 0, MinhaLista.size())
Definition at line 282 of file SortingAlgorithms.cxx.
00283 {
00284
if (BeginList < EndList -1)
00285
{
00286
int middle = (BeginList + EndList)/2;
00287
MergeMethod(ev, BeginList, middle);
00288
MergeMethod(ev, middle, EndList);
00289
Merges(ev, BeginList, middle, EndList);
00290
}
00291 }
Here is the call graph for this function:
ElementVector::clear
MergeSort::MergeMethod
MergeSort::Merges
ElementVector::resize
Here is the caller graph for this function:
MergeSort::MergeMethod
4.11.3.2
MergeSort::sort
void MergeSort::Merges (ElementVector & ev, int BeginList, int Middle, int EndList)
Método auxiliar ao MergeSort que executa a intercalação das listas. O método recebe vetores crescentes
v[BeginList..Middle-1] e v[Middle..EndList-1] e rearranja v[BeginList..EndList-1] em ordem crescente.
Definition at line 298 of file SortingAlgorithms.cxx.
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
52. 4.11 MergeSort Class Reference
49
00299 {
00300
int i, j, k;
00301
ElementVector w;
00302
00303
//Executa um resize na lista de elementos alocando o necessário para a
00304
//intercalação dos elementos.
00305
w.resize(EndList - BeginList);
00306
00307
//Estabelecendo os limites para a intercalação
00308
i = BeginList; j = Middle; k = 0;
00309
00310
//Verifica quem deve ser intercalado
00311
while( i < Middle && j < EndList)
00312
{
00313
if (ev[i] <= ev[j]) w[k++] = ev[i++];
00314
else w[k++] = ev[j++];
00315
00316
//Executa analise de desempenho do algoritmo.
00317
_numero_de_comparacoes++;
00318
_numero_de_trocas++;
00319
_numero_de_iteracoes++;
00320
}
00321
00322
//Executa as intercalações finais.
00323
while(i < Middle) { w[k++] = ev[i++]; _numero_de_iteracoes++; }
00324
while(j < EndList) { w[k++] = ev[j++]; _numero_de_iteracoes++; }
00325
00326
//Copia o a lista auxiliar para a lista original
00327
for( i = BeginList; i < EndList; ++i)
00328
{ ev[i] = w[i-BeginList]; _numero_de_iteracoes++; }
00329
00330
//Limpa a lista auxiliar ...
00331
w.clear();
00332 }
Here is the call graph for this function:
ElementVector::clear
MergeSort::Merges
ElementVector::resize
Here is the caller graph for this function:
MergeSort::Merges
4.11.3.3
MergeSort::MergeMethod
MergeSort::sort
void MergeSort::sort (ElementVector & ev) [virtual]
Método que executa a ordenação dos elementos.
Implements AbstractSorting.
Definition at line 269 of file SortingAlgorithms.cxx.
00269 { MergeMethod(ev, 0, ev.size()); };
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
53. 50
Class Documentation
Here is the call graph for this function:
ElementVector::clear
MergeSort::MergeMethod
MergeSort::Merges
MergeSort::sort
ElementVector::resize
ElementVector::size
The documentation for this class was generated from the following files:
• SortingAlgorithms.h
• SortingAlgorithms.cxx
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
54. 4.12 PredicateSort Struct Reference
4.12
PredicateSort Struct Reference
#include <Element.h>
Public Member Functions
• bool operator() (Element a, Element b)
4.12.1
Detailed Description
Estrutura auxiliar usada como predicado para executar ordenação usando o quicksort interno da STL.
Definition at line 68 of file Element.h.
4.12.2
Member Function Documentation
4.12.2.1
bool PredicateSort::operator() (Element a, Element b) [inline]
Definition at line 70 of file Element.h.
00070 { return a < b; }
The documentation for this struct was generated from the following file:
• Element.h
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
51
55. 52
4.13
Class Documentation
QuickPivotCentral Class Reference
#include <SortingAlgorithms.h>
Inheritance diagram for QuickPivotCentral:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
QuickPivotCentral
+ QuickPivotCentral()
+ sort()
+ QuickSort()
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
56. 4.13 QuickPivotCentral Class Reference
Collaboration diagram for QuickPivotCentral:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
QuickPivotCentral
+ QuickPivotCentral()
+ sort()
+ QuickSort()
Public Member Functions
• QuickPivotCentral ()
• void sort (ElementVector &ev)
• void QuickSort (ElementVector &ev, int BeginList, int EndList)
4.13.1
Detailed Description
Método de Ordenação QuickSort Nº 1 - Pivoteamento Central
Definition at line 233 of file SortingAlgorithms.h.
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
53
57. 54
Class Documentation
4.13.2
Constructor & Destructor Documentation
4.13.2.1
QuickPivotCentral::QuickPivotCentral () [inline]
Contructor
Definition at line 239 of file SortingAlgorithms.h.
00239 :AbstractSorting(){};
4.13.3
Member Function Documentation
4.13.3.1
void QuickPivotCentral::QuickSort (ElementVector & ev, int BeginList, int EndList)
Método de Ordenação QuickSort é um método de ordenação muito rápido e eficiente, inventado por C.A.R.
Hoare em 1960. O Quicksort é um algoritmo de ordenação não-estável que adota a estratégia de divisão
e conquista, podendo sofrer degeneração no melhor caso e caso médio [nlogn] para o pior caso [n∧ 2].
Essa implementação pode ser encontrada no livro de Sedgewick. O método rearranja o vetor v[p..r], com
p <= r+1, de modo que ele fique em ordem crescente.Esse método não se utiliza de um particionador
explicito e o pivo de verificação sempre é dado por um elemento central. Cuidado ao usar esse método,
o final da lista deve ser passado como size()-1, logo o mesmo deve ser chamado da seguinte forma :
QuickSort(MinhaLista, 0, MinhaLista.size() - 1)
Método de Ordenação QuickSort é um método de ordenação muito rápido e eficiente, inventado por C.A.R.
Hoare em 1960. O Quicksort é um algoritmo de ordenação não-estável que adota a estratégia de divisão e
conquista, podendo sofrer degeneração no melhor caso e caso médio [nlogn] para o pior caso [n∧ 2]. Essa
implementação pode ser encontrada no livro de Sedgewick. O método rearranja o vetor v[p..r], com p <=
r+1, de modo que ele fique em ordem crescente. Esse método não se utiliza de um particionador explicito
e o pivô de verificação sempre é dado por um elemento central.
Definition at line 182 of file SortingAlgorithms.cxx.
00183 {
00184
int i , j;
00185
Element c, t;
00186
00187
if (BeginList < EndList)
00188
{
00189
c = ev[(BeginList + EndList) / 2];
00190
i = BeginList; j = EndList;
00191
00192
while (i <= j)
00193
{
00194
while (ev[i] < c) { ++i; _numero_de_comparacoes++; _numero_de_iteracoes++;
}
00195
while (c < ev[j]) { --j; _numero_de_comparacoes++; _numero_de_iteracoes++;
}
00196
00197
if (i <= j)
00198
{
00199
t = ev[i], ev[i] = ev[j], ev[j] = t;
00200
++i, --j;
00201
_numero_de_trocas++;
00202
}
00203
_numero_de_iteracoes++;
00204
}
00205
00206
//Segmento onde ocorre a chamada recursiva ao método
00207
QuickSort(ev, BeginList, j);
00208
QuickSort(ev, i, EndList);
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
58. 4.13 QuickPivotCentral Class Reference
55
00209
}
00210 }
Here is the caller graph for this function:
QuickPivotCentral::QuickSort
4.13.3.2
QuickPivotCentral::sort
void QuickPivotCentral::sort (ElementVector & ev) [virtual]
Método que executa a ordenação dos elementos.
Implements AbstractSorting.
Definition at line 170 of file SortingAlgorithms.cxx.
00170 { QuickSort(ev, 0, ev.size() - 1); };
Here is the call graph for this function:
QuickPivotCentral::QuickSort
QuickPivotCentral::sort
ElementVector::size
The documentation for this class was generated from the following files:
• SortingAlgorithms.h
• SortingAlgorithms.cxx
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
59. 56
4.14
Class Documentation
QuickPivotPeripheral Class Reference
#include <SortingAlgorithms.h>
Inheritance diagram for QuickPivotPeripheral:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
QuickPivotPeripheral
+ QuickPivotPeripheral()
+ sort()
+ QSort()
+ Partition()
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
60. 4.14 QuickPivotPeripheral Class Reference
Collaboration diagram for QuickPivotPeripheral:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
QuickPivotPeripheral
+ QuickPivotPeripheral()
+ sort()
+ QSort()
+ Partition()
Public Member Functions
• QuickPivotPeripheral ()
• void sort (ElementVector &ev)
• void QSort (ElementVector &ev, int left, int right)
• int Partition (ElementVector &ev, int left, int right)
4.14.1
Detailed Description
Método de Ordenação QuickSort Nº 2 - Pivoteamento Periférico
Definition at line 265 of file SortingAlgorithms.h.
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
57
61. 58
Class Documentation
4.14.2
Constructor & Destructor Documentation
4.14.2.1
QuickPivotPeripheral::QuickPivotPeripheral () [inline]
Contructor
Definition at line 271 of file SortingAlgorithms.h.
00271 :AbstractSorting(){};
4.14.3
Member Function Documentation
4.14.3.1
int QuickPivotPeripheral::Partition (ElementVector & ev, int left, int right)
Método auxiliar ao QSort que executa particionamento da lista de elementos.
Definition at line 240 of file SortingAlgorithms.cxx.
00241 {
00242
register int i, j;
00243
00244
i = left;
00245
00246
for (j = left + 1; j <= right; j++)
00247
{
00248
_numero_de_iteracoes++;
00249
_numero_de_comparacoes++;
00250
if (ev[j] < ev[left])
00251
{
00252
++i;
00253
ev.swap(i,j);
00254
_numero_de_trocas++;
00255
}
00256
}
00257
00258
//O elemento do limite da partição é trocado com o pivô. Necessáriamente isso
00259
//é apenas uma reatribuição quando a lista já se encontra ordenada. Por isso
00260
//comentamos o incremento na variável de troca.
00261
//_numero_de_trocas++;
00262
ev.swap(left,i);
00263
return i;
00264 }
Here is the call graph for this function:
QuickPivotPeripheral::Partition
ElementVector::swap
Here is the caller graph for this function:
QuickPivotPeripheral::Partition
4.14.3.2
QuickPivotPeripheral::QSort
QuickPivotPeripheral::sort
void QuickPivotPeripheral::QSort (ElementVector & ev, int left, int right)
Método de ordenação quick sort que utiliza uma função de particionamento da lista de elementos. Esse
método utiliza um particionador explícito porém seu pivo de verificação não é um elemento central previaGenerated on Sun Dec 4 13:13:28 2011 by Doxygen
62. 4.14 QuickPivotPeripheral Class Reference
59
mente definido e sim os elementos que estam mais a direita de cada partição definida.Cuidado ao usar esse
método, o final da lista deve ser passado como size()-1, logo o mesmo deve ser chamado da seguinte forma
: QSort(MinhaLista, 0, MinhaLista.size() - 1)
Método de ordenação quick sort que utiliza uma função de particionamento da lista de elementos. Esse
método utiliza um particionador explícito porém seu pivo de verificação não é um elemento central previamente definido e sim elementos que se encontram mais a esquerda de cada partição definida.
Definition at line 223 of file SortingAlgorithms.cxx.
00224 {
00225
int new_right;
00226
00227
if (right > left)
00228
{
00229
new_right = Partition(ev, left, right);
00230
QSort(ev,left, new_right - 1);
00231
QSort(ev,new_right + 1,right);
00232
}
00233
00234
return;
00235 }
Here is the call graph for this function:
QuickPivotPeripheral::QSort
QuickPivotPeripheral::Partition
ElementVector::swap
Here is the caller graph for this function:
QuickPivotPeripheral::QSort
4.14.3.3
QuickPivotPeripheral::sort
void QuickPivotPeripheral::sort (ElementVector & ev) [virtual]
Método que executa a ordenação dos elementos.
Implements AbstractSorting.
Definition at line 215 of file SortingAlgorithms.cxx.
00215 { QSort(ev, 0, ev.size() - 1); };
Here is the call graph for this function:
QuickPivotPeripheral::QSort
QuickPivotPeripheral::Partition
QuickPivotPeripheral::sort
ElementVector::size
The documentation for this class was generated from the following files:
• SortingAlgorithms.h
• SortingAlgorithms.cxx
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
ElementVector::swap
63. 60
4.15
Class Documentation
SelectionSort Class Reference
#include <SortingAlgorithms.h>
Inheritance diagram for SelectionSort:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
SelectionSort
+ SelectionSort()
+ sort()
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
64. 4.15 SelectionSort Class Reference
61
Collaboration diagram for SelectionSort:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
SelectionSort
+ SelectionSort()
+ sort()
Public Member Functions
• SelectionSort ()
• void sort (ElementVector &ev)
4.15.1
Detailed Description
Método da ordenação por seleção que também possui complexidade quadrática porém em média se comporta melhor que a ordenação pelo método bolha.
Definition at line 216 of file SortingAlgorithms.h.
4.15.2
Constructor & Destructor Documentation
4.15.2.1
SelectionSort::SelectionSort () [inline]
Contructor
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
65. 62
Class Documentation
Definition at line 222 of file SortingAlgorithms.h.
00222 :AbstractSorting(){};
4.15.3
Member Function Documentation
4.15.3.1
void SelectionSort::sort (ElementVector & ev) [virtual]
Método que executa a ordenação dos elementos.
Método da ordenação por seleção que também possui complexidade quadrática porém em média se comporta melhor que a ordenação pelo método bolha.
Implements AbstractSorting.
Definition at line 143 of file SortingAlgorithms.cxx.
00144 {
00145
register unsigned int index,j,minimum;
00146
register unsigned int size_vector = ev.size();
00147
00148
for(j = 0; j < size_vector - 1; ++j)
00149
{
00150
minimum = j;
00151
00152
//Procura pelo índice com o menor elemento
00153
for(index = j+1; index < size_vector; ++index)
00154
{
00155
_numero_de_comparacoes++;
00156
_numero_de_iteracoes++;
00157
if (ev[index] < ev[minimum]) minimum = index;
00158
}
00159
00160
//Quando acha o menor elemento executa a troca. Necessáriamente isso é apenas
00161
//uma reatribuição quando a lista já se encontra ordenada.
00162
_numero_de_trocas++;
00163
ev.swap(j,minimum);
00164
}
00165 }
Here is the call graph for this function:
ElementVector::size
SelectionSort::sort
ElementVector::swap
The documentation for this class was generated from the following files:
• SortingAlgorithms.h
• SortingAlgorithms.cxx
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
66. 4.16 ShakerSort Class Reference
4.16
63
ShakerSort Class Reference
#include <SortingAlgorithms.h>
Inheritance diagram for ShakerSort:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
ShakerSort
+ ShakerSort()
+ sort()
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
67. 64
Class Documentation
Collaboration diagram for ShakerSort:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
ShakerSort
+ ShakerSort()
+ sort()
Public Member Functions
• ShakerSort ()
• void sort (ElementVector &ev)
4.16.1
Detailed Description
O Método de ordenação ShakerSort funciona como o Bubble Sort, mas de forma bidirecional e também é
conhecido como Cocktail Sort, possuindo complexidade quadrática, ou seja O(n∧ 2).
Definition at line 151 of file SortingAlgorithms.h.
4.16.2
Constructor & Destructor Documentation
4.16.2.1
ShakerSort::ShakerSort () [inline]
Contructor
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
68. 4.16 ShakerSort Class Reference
65
Definition at line 157 of file SortingAlgorithms.h.
00157 :AbstractSorting(){};
4.16.3
Member Function Documentation
4.16.3.1
void ShakerSort::sort (ElementVector & ev) [virtual]
Método que executa a ordenação dos elementos.
O Método de ordenação ShakerSort funciona como o Bubble Sort, mas de forma bidirecional e também é
conhecido como Cocktail Sort, possuindo complexidade quadrática, ou seja O(n∧ 2).
Implements AbstractSorting.
Definition at line 492 of file SortingAlgorithms.cxx.
00493 {
00494
//Declaração e atribuição das variaveis de controle
00495
int length, bottom, top, i; bool swapped = false;
00496
length = ev.size(); bottom = 0; top = length - 1; swapped = false;
00497
00498
//Se não houver troca de posições ou o ponteiro que
00499
//sobe ultrapassar o que desce, o vetor estará ordenado
00500
while(swapped == 0 && bottom < top)
00501
{
00502
swapped = true;
00503
00504
//Este looping é a ida para a direita
00505
for(i = bottom; i < top; i = i + 1)
00506
{
00507
//indo pra direita: testa se o próximo é maior
00508
//indo pra direita: se o proximo é maior que o atual troca as posições
00509
_numero_de_comparacoes++;
00510
_numero_de_iteracoes++;
00511
if(ev[i] > ev[i + 1])
00512
{
00513
ev.swap(i, i + 1);
00514
swapped = false;
00515
_numero_de_trocas++;
00516
}
00517
}
00518
00519
// Diminui o ‘top‘ porque o elemento com o maior valor
00520
// já está na direita (atual posição top)
00521
top = top - 1;
00522
00523
//Este looping é a ida para a esquerda
00524
for(i = top; i > bottom; i = i - 1)
00525
{
00526
_numero_de_comparacoes++;
00527
_numero_de_iteracoes++;
00528
if(ev[i] < ev[i - 1])
00529
{
00530
ev.swap(i, i - 1);
00531
swapped = false;
00532
_numero_de_trocas++;
00533
}
00534
}
00535
00536
//Aumenta o ‘bottom‘ porque o menor valor já está na posição inicial
00537
bottom = bottom + 1;
00538
}
00539 }
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
69. 66
Class Documentation
Here is the call graph for this function:
ElementVector::size
ShakerSort::sort
ElementVector::swap
The documentation for this class was generated from the following files:
• SortingAlgorithms.h
• SortingAlgorithms.cxx
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
70. 4.17 ShellSort Class Reference
4.17
67
ShellSort Class Reference
#include <SortingAlgorithms.h>
Inheritance diagram for ShellSort:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
ShellSort
+ ShellSort()
+ sort()
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
71. 68
Class Documentation
Collaboration diagram for ShellSort:
AbstractSorting
# _numero_de_iteracoes
# _numero_de_trocas
# _numero_de_comparacoes
+ AbstractSorting()
+ InitializeVariables()
+ IterationsNumber()
+ InversionsNumber()
+ ComparisonsNumber()
+ sort()
+ ~AbstractSorting()
ShellSort
+ ShellSort()
+ sort()
Public Member Functions
• ShellSort ()
• void sort (ElementVector &ev)
4.17.1
Detailed Description
Método Shell sort é o mais eficiente algoritmo de classificação dentre os de complexidade quadrática.
Basicamente o algoritmo passa várias vezes pela lista dividindo o grupo maior em menores. Nos grupos
menores é aplicado o método da ordenação por inserção. Dependendo da escolha do tamanho do salto
o algoritmo pode apresentar complexidade O(n∧ 2), O(n∗(logn)∧ 2) ou até mesmo O(n∗(logn)). Porém o
mesmo não deixa de ser classificado como um algoritmo da ordem O(n∧ 2).
Definition at line 341 of file SortingAlgorithms.h.
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
72. 4.17 ShellSort Class Reference
4.17.2
Constructor & Destructor Documentation
4.17.2.1
69
ShellSort::ShellSort () [inline]
Contructor
Definition at line 347 of file SortingAlgorithms.h.
00347 :AbstractSorting(){};
4.17.3
Member Function Documentation
4.17.3.1
void ShellSort::sort (ElementVector & ev) [virtual]
Método que executa a ordenação dos elementos.
Método Shell sort é o mais eficiente algoritmo de classificação dentre os de complexidade quadrática.
Basicamente o algoritmo passa várias vezes pela lista dividindo o grupo maior em menores. Nos grupos
menores é aplicado o método da ordenação por inserção. Dependendo da escolha do tamanho do salto
o algoritmo pode apresentar complexidade O(n∧ 2), O(n∗(logn)∧ 2) ou até mesmo O(n∗(logn)). Porém o
mesmo não deixa de ser classificado como um algoritmo da ordem O(n∧ 2).
Implements AbstractSorting.
Definition at line 343 of file SortingAlgorithms.cxx.
00344 {
00345
int h, size = ev.size();
00346
00347
for( h = 1; h < size; h = 3 * h + 1 );
00348
00349
do
00350
{
00351
//Tamanho do gap ou salto que sera dado de 3 em 3 dentro do compartimento...
00352
h /= 3;
00353
00354
//Executando looping para verificação e ordenação ...
00355
for( int i = h; i < size; ++i )
00356
{
00357
Element value = ev[i];
00358
int j;
00359
00360
//O algoritmo faz pelo menos uma comparação antes de entrar no looping e um
a
00361
//iteração pois se as condições do cabeçalho condicional do próximo laço nã
o
00362
//forem aceitas o looping[for] não será executado.
00363
_numero_de_iteracoes++;
00364
_numero_de_comparacoes++;
00365
00366
for( j = i - h; j >= 0 && value < ev[j]; j -= h )
00367
{
00368
ev[j+h] = ev[j];
00369
_numero_de_iteracoes++;
00370
_numero_de_trocas++;
00371
_numero_de_comparacoes++;
00372
}
00373
00374
_numero_de_trocas++;
00375
ev[j+h] = value;
00376
}
00377
}while( h > 1 );
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
73. 70
Class Documentation
00378
00379 }
Here is the call graph for this function:
ShellSort::sort
ElementVector::size
The documentation for this class was generated from the following files:
• SortingAlgorithms.h
• SortingAlgorithms.cxx
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
74. Chapter 5
File Documentation
5.1
Element.cxx File Reference
#include "Element.h"
#include <vector>
#include <cmath>
#include <algorithm>
Include dependency graph for Element.cxx:
Element.cxx
vector
cmath
algorithm
This graph shows which files directly or indirectly include this file:
Element.cxx
75. 72
5.2
00001
00002
00003
00004
00005
00006
00007
00008
00009
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043
00044
00045
00046
00047
00048
00049
00050
00054
00055
00056
File Documentation
Element.cxx
/*
* _Element.cpp
*
* Created on: 25/10/2009
Author: Administrador
*
*/
#include "Element.h"
long double ElementVector::maxValue(void)
{
//Verificando se a lista foi preenchida ...
if (_list.size() == 0 ) return 0;
//Resgatando o primeiro elemento da lista para verificação do maior elemento
long double maximo = at(0).value();
//Looping para verificação do maior elemento
for (unsigned int index = 1; index < _list.size(); index++)
{
if (maximo < at(index).value()) maximo = at(index).value();
}
//Retornando o maior valor da lista
return maximo;
}
long double ElementVector::minValue(void)
{
//Verificando se a lista foi preenchida ...
if (_list.size() == 0 ) return 0;
//Resgatando o primeiro elemento da lista para verificação do maior elemento
long double minimo = at(0).value();
//Looping para verificação do maior elemento
for (unsigned int index = 1; index < _list.size(); index++)
{
if (minimo > at(index).value()) minimo = at(index).value();
}
//Retornando o maior valor da lista
return minimo;
}
long double ElementVector::absMaxValue(void)
{
return (fabsl(maxValue()) > fabsl(minValue()))?(maxValue()):(fabsl(minValue()))
;
00057 }
00058
00063 void ElementVector::swap(unsigned int position_a, unsigned int position_b)
00064 {
00065
//Executa a troca dos valores
00066
long double temp = _list[position_a].value();
00067
_list[position_a].value( _list[position_b].value() );
00068
_list[position_b].value(temp);
00069 }
00070
00071
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
76. 5.3 Element.h File Reference
5.3
73
Element.h File Reference
#include <vector>
#include <cmath>
#include <algorithm>
Include dependency graph for Element.h:
Element.h
vector
cmath
algorithm
This graph shows which files directly or indirectly include this file:
Element.h
SortingAlgorithms.cxx
SortingAlgorithms.h
Sys-LibrarySorting.cpp
Classes
• class Element
• struct PredicateSort
• class ElementVector
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
78. 5.4 Element.h
00137
00141
void push_back(Element e) { _list.push_back(e); }
00142
00146
void add(Element e)
{ this->push_back(e); }
00147
00152
void swap(unsigned int position_a, unsigned int position_b);
00153
00157
void clear(void) { _list.clear(); }
00158
00163
virtual ~ElementVector(){ clear(); }
00164 };
00165
00166 #endif /* _ELEMENT_H_ */
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
75
79. 76
5.5
File Documentation
SortingAlgorithms.cxx File Reference
#include "SortingAlgorithms.h"
#include "Element.h"
#include <iostream>
Include dependency graph for SortingAlgorithms.cxx:
SortingAlgorithms.cxx
Element.h
vector
cmath
iostream
algorithm
This graph shows which files directly or indirectly include this file:
SortingAlgorithms.cxx
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
80. 5.6 SortingAlgorithms.cxx
5.6
00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00016
00017
00018
00019
00020
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00043
00044
00045
00046
00047
00048
00049
00050
00051
00052
00053
00054
00055
00056
00057
00058
00059
00060
00061
00062
00063
00064
00072
00073
00074
00075
00076
00077
00078
00079
00080
00081
00082
00083
00084
00085
00086
00087
SortingAlgorithms.cxx
/*
* SortingAlgorithms.cpp
*
* Created on: 26/10/2009
Author: Administrador
*
*/
#include "SortingAlgorithms.h"
//--------------------------------------------------------------------------/* Classe base para uso do padrão strategy.*/
//--------------------------------------------------------------------------AbstractSorting::AbstractSorting()
{
InitializeVariables();
}
void AbstractSorting::InitializeVariables(void)
{
_numero_de_iteracoes
= 0;
_numero_de_trocas
= 0;
_numero_de_comparacoes = 0;
}
//--------------------------------------------------------------------------/* Classes de ordenação .*/
//--------------------------------------------------------------------------void BubbleSort::sort(ElementVector & ev)
{
//std::cout << "Bubble..." << std::endl;
register unsigned int i,j;
//executa loopings para varrer a lista de números
for (i = 1; i < ev.size(); ++i)
{
for(j = ev.size()-1; j >= i; --j)
{
//executa troca caso encontre elementos desordenados
if ( ev[j-1] > ev[j] )
{
ev.swap(j-1,j);
_numero_de_trocas++;
}
_numero_de_comparacoes++;
_numero_de_iteracoes++;
}
}
}
void BubbleSort2::sort(ElementVector & ev)
{
bool houvetroca = false;
register unsigned int index = 0;
register unsigned int size_vector = ev.size();
while ((!houvetroca) && (index < size_vector - 1))
{
index = 0;
while(index < size_vector - 1)
{
//Verifica o número de comparações realizadas
_numero_de_comparacoes++;
//Verifica se algum elemento deve sofrer inversão
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
77
81. 78
00088
00089
00090
00091
00092
00093
00094
00095
00096
00097
00098
00099
00100
00101
00102
00107
00108
00109
00110
00111
00112
00113
00114
00115
00116
00117
00118
00119
00120
00121
00122
00123
00124
00125
00126
00127
00128
00129
00130
00131
00132
00133
00134
00135
00136
00137
00138
00143
00144
00145
00146
00147
00148
00149
00150
00151
00152
00153
00154
00155
00156
00157
00158
00159
00160
00161
File Documentation
if (ev[index] > ev[index + 1])
{
ev.swap(index + 1,index);
houvetroca = true;
_numero_de_trocas++;
}
//Caso haja troca retorna o indice para o começo da lista
if(houvetroca) { index = 0; houvetroca = false; }
else { ++index;}
_numero_de_iteracoes++;
}
}
}
void InsertionSort::sort(ElementVector & ev)
{
Element temp;
int index;
unsigned int j, size_vector = ev.size();
for(j = 1; j < size_vector; j++)
{
temp = ev[j];
//O algoritmo faz pelo menos uma comparação antes de entrar no looping e uma
//iteração pois se as condições do cabeçalho condicional do próximo laço não
//forem aceitas o looping[for] não será executado.
_numero_de_iteracoes++;
_numero_de_comparacoes++;
//O restante das comparações são feitas pelo cabeçalho condicional do laço
for(index = j-1; index >= 0 && ev[index] > temp; index--)
{
ev[index + 1] = ev[index];
_numero_de_iteracoes++;
_numero_de_trocas++;
_numero_de_comparacoes++;
}
//Necessáriamente isso é apenas uma reatribuição quando a lista já se
//encontra ordenada, por isso comentamos o incremento do número de trocas
//_numero_de_trocas++;
ev[index + 1] = temp;
}
}
void SelectionSort::sort(ElementVector & ev)
{
register unsigned int index,j,minimum;
register unsigned int size_vector = ev.size();
for(j = 0; j < size_vector - 1; ++j)
{
minimum = j;
//Procura pelo índice com o menor elemento
for(index = j+1; index < size_vector; ++index)
{
_numero_de_comparacoes++;
_numero_de_iteracoes++;
if (ev[index] < ev[minimum]) minimum = index;
}
//Quando acha o menor elemento executa a troca. Necessáriamente isso é apenas
//uma reatribuição quando a lista já se encontra ordenada.
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
82. 5.6 SortingAlgorithms.cxx
79
00162
_numero_de_trocas++;
00163
ev.swap(j,minimum);
00164
}
00165 }
00166
00170 void QuickPivotCentral::sort(ElementVector& ev){ QuickSort(ev, 0, ev.size() - 1)
; };
00171
00182 void QuickPivotCentral::QuickSort(ElementVector& ev, int BeginList, int EndList)
00183 {
00184
int i , j;
00185
Element c, t;
00186
00187
if (BeginList < EndList)
00188
{
00189
c = ev[(BeginList + EndList) / 2];
00190
i = BeginList; j = EndList;
00191
00192
while (i <= j)
00193
{
00194
while (ev[i] < c) { ++i; _numero_de_comparacoes++; _numero_de_iteracoes++;
}
00195
while (c < ev[j]) { --j; _numero_de_comparacoes++; _numero_de_iteracoes++;
}
00196
00197
if (i <= j)
00198
{
00199
t = ev[i], ev[i] = ev[j], ev[j] = t;
00200
++i, --j;
00201
_numero_de_trocas++;
00202
}
00203
_numero_de_iteracoes++;
00204
}
00205
00206
//Segmento onde ocorre a chamada recursiva ao método
00207
QuickSort(ev, BeginList, j);
00208
QuickSort(ev, i, EndList);
00209
}
00210 }
00211
00215 void QuickPivotPeripheral::sort(ElementVector& ev){ QSort(ev, 0, ev.size() - 1);
};
00216
00223 void QuickPivotPeripheral::QSort(ElementVector& ev, int left, int right)
00224 {
00225
int new_right;
00226
00227
if (right > left)
00228
{
00229
new_right = Partition(ev, left, right);
00230
QSort(ev,left, new_right - 1);
00231
QSort(ev,new_right + 1,right);
00232
}
00233
00234
return;
00235 }
00236
00240 int QuickPivotPeripheral::Partition(ElementVector& ev, int left, int right)
00241 {
00242
register int i, j;
00243
00244
i = left;
00245
00246
for (j = left + 1; j <= right; j++)
00247
{
00248
_numero_de_iteracoes++;
00249
_numero_de_comparacoes++;
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
83. 80
00250
00251
00252
00253
00254
00255
00256
00257
00258
00259
00260
00261
00262
00263
00264
00265
00269
00270
00282
00283
00284
00285
00286
00287
00288
00289
00290
00291
00292
00298
File Documentation
if (ev[j] < ev[left])
{
++i;
ev.swap(i,j);
_numero_de_trocas++;
}
}
//O elemento do limite da partição é trocado com o pivô. Necessáriamente isso
//é apenas uma reatribuição quando a lista já se encontra ordenada. Por isso
//comentamos o incremento na variável de troca.
//_numero_de_trocas++;
ev.swap(left,i);
return i;
}
void MergeSort::sort(ElementVector& ev){ MergeMethod(ev, 0, ev.size()); };
void MergeSort::MergeMethod(ElementVector& ev, int BeginList, int EndList)
{
if (BeginList < EndList -1)
{
int middle = (BeginList + EndList)/2;
MergeMethod(ev, BeginList, middle);
MergeMethod(ev, middle, EndList);
Merges(ev, BeginList, middle, EndList);
}
}
void MergeSort::Merges(ElementVector & ev, int BeginList, int Middle, int EndList
)
00299 {
00300
int i, j, k;
00301
ElementVector w;
00302
00303
//Executa um resize na lista de elementos alocando o necessário para a
00304
//intercalação dos elementos.
00305
w.resize(EndList - BeginList);
00306
00307
//Estabelecendo os limites para a intercalação
00308
i = BeginList; j = Middle; k = 0;
00309
00310
//Verifica quem deve ser intercalado
00311
while( i < Middle && j < EndList)
00312
{
00313
if (ev[i] <= ev[j]) w[k++] = ev[i++];
00314
else w[k++] = ev[j++];
00315
00316
//Executa analise de desempenho do algoritmo.
00317
_numero_de_comparacoes++;
00318
_numero_de_trocas++;
00319
_numero_de_iteracoes++;
00320
}
00321
00322
//Executa as intercalações finais.
00323
while(i < Middle) { w[k++] = ev[i++]; _numero_de_iteracoes++; }
00324
while(j < EndList) { w[k++] = ev[j++]; _numero_de_iteracoes++; }
00325
00326
//Copia o a lista auxiliar para a lista original
00327
for( i = BeginList; i < EndList; ++i)
00328
{ ev[i] = w[i-BeginList]; _numero_de_iteracoes++; }
00329
00330
//Limpa a lista auxiliar ...
00331
w.clear();
00332 }
00333
00343 void ShellSort::sort(ElementVector& ev)
Generated on Sun Dec 4 13:13:28 2011 by Doxygen
84. 5.6 SortingAlgorithms.cxx
81
00344 {
00345
int h, size = ev.size();
00346
00347
for( h = 1; h < size; h = 3 * h + 1 );
00348
00349
do
00350
{
00351
//Tamanho do gap ou salto que sera dado de 3 em 3 dentro do compartimento...
00352
h /= 3;
00353
00354
//Executando looping para verificação e ordenação ...
00355
for( int i = h; i < size; ++i )
00356
{
00357
Element value = ev[i];
00358
int j;
00359
00360
//O algoritmo faz pelo menos uma comparação antes de entrar no looping e um
a
00361
//iteração pois se as condições do cabeçalho condicional do próximo laço nã
o
00362
//forem aceitas o looping[for] não será executado.
00363
_numero_de_iteracoes++;
00364
_numero_de_comparacoes++;
00365
00366
for( j = i - h; j >= 0 && value < ev[j]; j -= h )
00367
{
00368
ev[j+h] = ev[j];
00369
_numero_de_iteracoes++;
00370
_numero_de_trocas++;
00371
_numero_de_comparacoes++;
00372
}
00373
00374
_numero_de_trocas++;
00375
ev[j+h] = value;
00376
}
00377
}while( h > 1 );
00378
00379 }
00380
00393 void HeapSort::sort(ElementVector & ev)
00394 {
00395
int i = ev.size()/2, n = ev.size(), pai, filho;
00396
Element t;
00397
00398
for (;;)
00399
{
00400
if (i > 0)
00401
{
00402
i--;
00403
t = ev[i];
00404
}
00405
else
00406
{
00407
n--;
00408
if (n == 0) return;
00409
t = ev[n];
00410
ev[n] = ev[0];
00411
}
00412
00413
pai = i;
00414
filho = i*2 + 1;
00415
00416
while (filho < n)
00417
{
00418
if ((filho + 1 < n) && (ev[filho + 1] > ev[filho]))
00419
{
00420
filho++;
Generated on Sun Dec 4 13:13:28 2011 by Doxygen