Algoritmos em JavaScript Explica Algoritmos de JavaScript Com Belas Imagens Aprenda Mais Fácil e Melhor - Yang Hu
Algoritmos em JavaScript Explica Algoritmos de JavaScript Com Belas Imagens Aprenda Mais Fácil e Melhor - Yang Hu
YANG HU
Aprenda fácil, rápido e bem.
http://br.verejava.com
Copyright © 2021 Yang Hu All rights reserved.
ISBN: 9798595201131
CONTEÚDO
1. Definição de tabela linear
2. Anexar tabela linear
3. Inserção de mesa linear
4. Tabela linear Excluir
5. Algoritmo de Ordenar de bolhas
6. Valor Mínimo
7. Selecione o algoritmo de Ordenar
8. Inserir algoritmo de Ordenar
9. Mesa Linear Reversa
10. Pesquisa de tabela linear
11. Algoritmo de pesquisa de dicotomia
12. Classificação de cascas
13. Lista vinculada única
13.1 Criar e Inicialização
13.2 Adicionar nó
13.3 Inserir nó
13.4 Excluir nó
14. Lista duplamente vinculada
14.1 Criar e Inicialização
14.2 Adicionar nó
14.3 Inserir nó
14.4 Excluir nó
15. Lista vinculada circular unidirecional
15.1 Criar e Inicialização
15.2 Inserir nó
15.3 Excluir nó
16. Lista vinculada circular de duas vias
16.1 Criar e Inicialização
16.2 Inserir nó
16.3 Excluir nó
17. Fila
18. Pilha
19. Algoritmo Recursivo
20. Algoritmo de Ordenar rápida
21. Algoritmo de mesclagem bidirecional
22. Árvore de pesquisa binária
22.1 Construir uma árvore de pesquisa binária
22.2 Árvore de pesquisa binária In-order traversal
22.3 Árvore de pesquisa binária Pre-order traversal
22.4 Árvore de pesquisa binária Post-order traversal
22.5 Árvore de pesquisa binária Máximo e mínimo
22.6 Árvore de pesquisa binária Excluir nó
23. Ordenar da pilha
24. Tabela de hash
25. Gráfico
25.1 Gráfico direcionado e pesquisa em
profundidade
25.2 Gráfico dirigido e Primeira pesquisa de largura
25.3 Ordenar topológica
26. Torres de Hanói
27. Fibonacci
28. Dijkstra
29. Labirinto de caminhada do rato
30. Eight Coins
31. Josephus Problem
Definição de tabela linear
Tabela Linear (Linear Table): Uma sequência de zero ou mais elementos
de dados. Além do primeiro elemento, cada elemento possui apenas um
elemento precursor direto e cada elemento possui apenas um elemento
sucessor direto, exceto o último. A relação entre os elementos de dados é de
um para um. As tabelas lineares podem ser representadas por matrizes
unidimensionais.
<script type="text/javascript"> var scores = new Array( 90, 70, 50, 80,
60, 85 );
for (var i = 0; i < scores.length; i++) {
document.write(scores[i] + ","); }
</script>
Resultado:
Anexar tabela linear
1. Adicione 75 ao final da matriz unidimensional.
<script type="text/javascript">
function append(array, value) {
var tempArray = new Array(array.length + 1); // Crie um tempArray
maior que array
for (var i = 0; i < array.length; i++) {
tempArray[i] = array[i]; // Copie o valor da matriz para tempArray }
tempArray[array.length] = value// Insira o valor para o último índice
return tempArray; }
//////////////////////testing////////////////////
var scores = new Array( 90, 70, 50, 80, 60, 85 );
scores = append(scores, 75);
for (var i = 0; i < scores.length; i++) {
document.write(scores[i] + ","); }
</script>
<script type="text/javascript">
function insert(array, score, insertIndex) {
var tempArray = new Array(array.length + 1); for (var i = 0; i <
array.length; i++) {
if (i < insertIndex) {
tempArray[i] = array[i]; // Copie o valor anterior a i = insertIndex para
tempArray } else {
tempArray[i + 1] = array[i]; // Copie os elementos restantes para
tempArray }
}
tempArray[insertIndex] = score; return tempArray; }
//////////////////////testing////////////////////
var scores = new Array( 90, 70, 50, 80, 60, 85 );
scores = insert(scores, 75, 2); // Insira 75 na posição: index = 2
</script>
Resultado:
90,70,75,50, 80, 60, 85,
Tabela linear Excluir
1. Exclua o valor do índice = 2 da matriz
<script type="text/javascript">
function remove(array, index){
// crie uma nova matriz, length = scores.length - 1
var tempArray = new Array(array.length - 1);
for (var i = 0; i < array.length; i++) {
if (i < index) // Copie os dados anteriores a i = index para tempArray.
tempArray[i] = array[i]; if (i > index) // Copie a matriz após i = index
para o final de tempArray tempArray[i - 1] = array[i]; }
return tempArray; }
//////////////////////testing////////////////////
var scores = new Array( 90, 70, 50, 80, 60, 85 );
scores = remove(scores, 2); // remova o valor da matriz no índice = 2
</script>
Resultado:
90,70,80,60,85,
Algoritmo de Ordenar de bolhas
Algoritmo de Ordenar de bolhas (Bubble Sorting Algorithm): se arrays
[j]> arrays [j + 1] forem trocados. Os elementos restantes repetem esse
processo até a Ordenar ser concluída.
Sem Ordenar,
Comparando,
Já Ordenar
1. Primeira Ordenar:
2. Segunda Ordenar:
3. Terceira Ordenar:
<script type="text/javascript">
function sort(arrays) {
for (var i = 0; i < arrays.length - 1; i++) {
var isSwap = false; for (var j = 0; j < arrays.length - i - 1; j++) {
// troca if (arrays[j] > arrays[j + 1]) {
var flag = arrays[j]; arrays[j] = arrays[j + 1]; arrays[j + 1] = flag;
isSwap = true; }
}
Resultado:
50,60,70,80,95,
Valor Mínimo
Pesquisar o mínimo de sequências inteiras:
1. Ideias algorítmicas
Valor inicial minIndex=0, j=1 Compare arrays[minIndex] com arrays[j]
if arrays[minIndex] > arrays[j] then minIndex=j, j++ else j++. continue até
o último número, arrays[minIndex] é o valor mínimo.
1. Crie um TestMinValue.html com o Bloco de notas e abra-o em seu
navegador.
//////////////////////testing////////////////////
Resultado:
Min Value = 50
Selecione o algoritmo de Ordenar
Selecione o algoritmo de Ordenar (Select Sorting Algorithm):
Classifica uma matriz localizando repetidamente o elemento mínimo de
uma parte não classificada e colocando-a no início.
Sem Ordenar,
Comparando,
Já Ordenar
1. Primeira Ordenar:
2. Segunda Ordenar:
3. Terceira Ordenar:
4. Quarta Ordenar:
<script type="text/javascript">
class SelectSort{
static sort(arrays) {
var len = arrays.length - 1; var minIndex;// O índice do mínimo
selecionado
for (var i = 0; i < len; i++) {
minIndex = i; var minValue = arrays[minIndex]; for (var j = i; j < len;
j++) {
if (minValue > arrays[j + 1]) {
minValue = arrays[j + 1]; minIndex = j + 1; }
}
//////////////////////testing////////////////////
var scores = [ 90, 70, 50, 80, 60, 85 ];
SelectSort.sort(scores);
for (var i = 0; i < scores.length; i++) {
document.write(scores[i] + ","); }
</script>
Resultado:
50,60,70,80,95,
Inserir algoritmo de Ordenar
Inserir algoritmo de Ordenar (Insert Sorting Algorithm): Pegue um
novo elemento não classificado na matriz, compare-o com o elemento já
classificado antes, se o elemento for menor que o elemento classificado,
insira um novo elemento na posição correta.
Explicação:
2. Segunda Ordenar:
3. Terceira Ordenar:
4 Quarta Ordenar:
1. Crie um TestInsertSort.html com o Bloco de notas e abra-o em seu
navegador.
<script type="text/javascript">
class InsertSort{
static sort(arrays) {
for (var i = 0; i < arrays.length; i++) {
var insertElement = arrays[i];// Pegue novos elementos não
classificados var insertPosition = i; for (var j = insertPosition - 1; j >= 0;
j--) {
// insertElement é deslocado para a direita if (insertElement < arrays[j])
{
arrays[j + 1] = arrays[j]; insertPosition--; }
}
arrays[insertPosition] = insertElement; }
}
}
//////////////////////testing////////////////////
Resultado:
50,60,70,80,95,
Mesa Linear Reversa
Inversão de sequências ordenadas:
1. Ideias algorítmicas
Inicial i = 0 e, em seguida, troque o primeiro elemento pelo último elemento
Repita até o índice do meio i == length / 2.
1. Crie um TestReverse.html com o Bloco de notas e abra-o em seu
navegador.
//////////////////////testing////////////////////
</script>
Resultado:
90,80,70,60,50,
Pesquisa de tabela linear
1. Digite 70 que deseja pesquisar e depois retorne o índice.
<script type="text/javascript">
function search(array, value){
for (var i = 0; i < array.length; i++) {
if (array[i] == value) {
return i; }
}
return -1; }
//////////////////////testing////////////////////
var scores = new Array( 90, 70, 50, 80, 60, 85 ); var value = 70; var
index = search(scores, value);
if (index > 0) {
document.write("Found value: " + value + " the index is: " + index);
}else{
document.write("The value was not found : " + value); }
</script>
Resultado:
Found value: 70 the index is: 1
Algoritmo de pesquisa de dicotomia
Algoritmo de pesquisa de dicotomia (Dichotomy Search Algorithm): O
algoritmo de pesquisa binária, também conhecido como algoritmo de
pesquisa binária e algoritmo de pesquisa logarítmica, é um algoritmo de
pesquisa para encontrar um elemento específico em uma matriz ordenada.
O processo de pesquisa inicia no elemento do meio da matriz. Se o
elemento do meio for o elemento a ser encontrado, o processo de pesquisa
será encerrado; se um elemento em particular for maior que ou menor que o
elemento do meio, ele será encontrado na metade da matriz que é maior ou
menor que o elemento do meio, e Comece com o elemento do meio como
antes..
//////////////////////testing////////////////////
var scores = [ 30, 40, 50, 70, 85, 90, 100 ];
var searchValue = 40; var position = BinarySearch.search(scores,
searchValue); document.write(searchValue + " position:" + position);
document.write("<br>-----------------------------<br>");
searchValue = 90; position = BinarySearch.search(scores,
searchValue); document.write(searchValue + " position:" + position);
</script>
Resultado:
40 position:1
-----------------------------
90 position:5
Classificação de cascas
Classificação de cascas (Shell Sorting):
A classificação shell é um algoritmo de classificação altamente eficiente e é
baseado no algoritmo de classificação por inserção. Este algoritmo evita
grandes deslocamentos como no caso da classificação por inserção, se o
valor menor estiver na extrema direita e tiver que ser movido na extrema
esquerda.
Resultado do algoritmo:
O array é agrupado de acordo com um certo incremento de subscritos, e a
inserção de cada grupo é ordenada. Conforme o incremento diminui
gradualmente até que o incremento seja 1, todos os dados são agrupados e
classificados.
1. A primeira classificação :
gap = array.length / 2 = 5
2. A segunda classificação :
gap = 5 / 2 = 2
3. A terceira classificação :
gap = 2 / 2 = 1
1. Crie um TestShellSort.html com o Bloco de notas e abra-o em seu
navegador.
<script type="text/javascript">
function shellSort(array) {
var middle = parseInt(array.length / 2);
for (var gap =middle ; gap > 0; gap = parseInt(gap / 2)) {
for (var i = gap; i < array.length; i++) {
var j = i;
while (j - gap >= 0 && array[j] < array[j - gap]) {
swap(array, j, j - gap);
j = j - gap;
}
}
}
}
function swap(array, a, b) {
array[a] = array[a] + array[b];
array[b] = array[a] - array[b];
array[a] = array[a] - array[b];
}
//////////////////////testing////////////////////
var scores = [ 9, 6, 5, 8, 0, 7, 4, 3, 1, 2 ];
shellSort(scores);
</script>
Resultado:
0,1,2,3,4,5,6,7,8,9,
Lista vinculada única
Lista vinculada única (Single Linked List): É uma estrutura de
armazenamento encadeado de uma tabela linear, que é conectada por um
nó. Cada nó consiste em dados e ponteiro para o próximo nó.
UML Diagrama
class Node{
constructor(data, next){
this.data = data; this.next = next; }
getData(){
return this.data; }
}
1. Inicialização de lista vinculada única .
Exemplo: Construir uma lista vinculada única
class LinkedList{
init() {
// o primeiro nó chamado cabe?a nó this.head = new Node("A", null);
var nodeB = new Node("B", null); this.head.next = nodeB; var nodeC =
new Node("C", null); nodeB.next = nodeC; // o último nó chamado nó da
cauda this.tail = new Node("D", null); nodeC.next = this.tail; }
}
2. Saída de lista vinculada única .
1. Crie um TestSingleLinkList.html com o Bloco de notas e abra-o em
seu navegador.
<script type="text/javascript">
/////////////// Node /////////////////
class Node{
constructor(data, next){
this.data = data; this.next = next; }
getData(){
return this.data; }
}
init() {
// o primeiro nó chamado cabe?a nó this.head = new Node("A", null);
var nodeB = new Node("B", null); this.head.next = nodeB;
var nodeC = new Node("C", null); nodeB.next = nodeC;
// o último nó chamado nó da cauda this.tail = new Node("D", null);
nodeC.next = this.tail; }
getHead(){
return this.head; }
function print(node) {
var p = node; while (p != null) // Imprimir do início ao fim {
var data = p.getData(); document.write(data + " -> "); p = p.next; }
document.write("End<br><br>"); }
add(newNode) {
this.tail.next = newNode;
this.tail = newNode;
}
1. Crie um arquivo: TestSingleLinkList.html
<script type="text/javascript">
/////////////// Node /////////////////
class Node{
constructor(data, next){
this.data = data; this.next = next; }
getData(){
return this.data; }
}
init() {
// o primeiro nó chamado cabe?a nó this.head = new Node("A", null);
var nodeB = new Node("B", null); this.head.next = nodeB;
var nodeC = new Node("C", null); nodeB.next = nodeC;
// o último nó chamado nó da cauda this.tail = new Node("D", null);
nodeC.next = this.tail; }
add(newNode) {
this.tail.next = newNode; this.tail = newNode; }
getHead(){
return this.head; }
}
function print(node) {
var p = node; while (p != null) // Imprimir do início ao fim {
var data = p.getData(); document.write(data + " -> "); p = p.next; }
document.write("End<br><br>"); }
var linkedList = new LinkedList();
linkedList.init();
linkedList.add(new Node("E", null)); // Anexe um novo nó: E
print(linkedList.getHead());
</script>
getData(){
return this.data; }
}
init() {
// o primeiro nó chamado cabe?a nó this.head = new Node("A", null);
var nodeB = new Node("B", null); this.head.next = nodeB;
var nodeC = new Node("C", null); nodeB.next = nodeC;
// o último nó chamado nó da cauda this.tail = new Node("D", null);
nodeC.next = this.tail; }
insert(insertPosition, newNode) {
var p = this.head; var i = 0; // Mova o nó para a posição de inserção
while (p.next != null && i < insertPosition - 1) {
p = p.next; i++; }
getHead(){
return this.head; }
}
function print(node) {
var p = node; while (p != null) // Imprimir do início ao fim {
var data = p.getData(); document.write(data + " -> "); p = p.next; }
document.write("End<br><br>"); }
var linkedList = new LinkedList();
linkedList.init();
linkedList.insert(2, new Node("E", null)) // Insira um novo nó: E
print(linkedList.getHead());
</script>
Resultado: A -> B -> E -> C -> D -> End
4. Exclua o índice = 2 nós.
1. Crie um arquivo: TestSingleLinkList.html
<script type="text/javascript"> class Node{
constructor(data, next){
this.data = data; this.next = next; }
getData(){
return this.data; }
}
/////////////// LinkedList /////////////////
class LinkedList{
init() {
this.head = new Node("A", null); // o primeiro nó chamado cabe?a nó
var nodeB = new Node("B", null); this.head.next = nodeB;
var nodeC = new Node("C", null); nodeB.next = nodeC;
this.tail = new Node("D", null); // o último nó chamado nó da cauda
nodeC.next = this.tail; }
remove(removePosition) {
var p = this.head; var i = 0; // Mova o nó para a posição do nó anterior
que deseja excluir while (p.next != null && i < removePosition - 1) {
p = p.next; i++; }
var temp = p.next; p.next = p.next.next; temp.next = null; }
getHead(){
return this.head; }
}
/////////////////// test ////////////////////
function print(node) {
var p = node; while (p != null) // Imprimir do início ao fim {
var data = p.getData(); document.write(data + " -> "); p = p.next; }
document.write("End<br><br>"); }
UML Diagrama
class Node{
constructor(data, prev, next){
this.data = data; this.prev = prev; this.next = next; }
getData(){
return this.data; }
}
1. Inicialização de lista duplamente vinculada .
Exemplo: Construir uma lista vinculada
class DoubleLinkList{
init() {
this.head = new Node("A"); //o primeiro nó chamado cabe?a nó
this.head.prev = null; this.head.next = null;
var nodeB = new Node("B"); nodeB.prev = this.head; nodeB.next =
null; this.head.next = nodeB;
var nodeC = new Node("C"); nodeC.prev = nodeB; nodeC.next = null;
nodeB.next = nodeC;
this.tail = new Node("D"); //o último nó chamado nó da cauda
this.tail.prev = nodeC; this.tail.next = null; nodeC.next = this.tail; }
}
2. Crie um arquivo: TestDoubleLink.html
getData(){
return this.data; }
}
init() {
this.head = new Node("A"); //o primeiro nó chamado cabe?a nó
this.head.prev = null; this.head.next = null;
var nodeB = new Node("B"); nodeB.prev = this.head; nodeB.next =
null; this.head.next = nodeB;
var nodeC = new Node("C"); nodeC.prev = nodeB; nodeC.next = null;
nodeB.next = nodeC;
this.tail = new Node("D"); //o último nó chamado nó da cauda
this.tail.prev = nodeC; this.tail.next = null; nodeC.next = this.tail; }
getHead(){
return this.head; }
}
function print(node) {
var p = node; var end = null; while (p != null){ // Imprimir do início
ao fim var data = p.getData(); document.write(data + " -> "); end = p; p
= p.next; }
document.write("End <br><br>");
p = end; while (p != null){ // Imprimir do final ao início var data =
p.getData(); document.write(data + " -> "); p = p.prev; }
document.write("Start<br><br>"); }
add(newNode) {
this.tail.next = newNode;
newNode.prev = this.tail;
this.tail = newNode;
}
Crie um arquivo: TestDoubleLinkAdd.html
getData(){
return this.data; }
}
add(newNode) {
this.tail.next = newNode; newNode.prev = this.tail; this.tail =
newNode; }
getHead(){
return this.head; }
}
print(doubleLinkList.getHead()); </script>
Resultado: A -> B -> C -> D -> E -> End
E -> D -> C -> B -> A -> Start
3. Insira um nó E na posição 2.
Crie um arquivo: TestDoubleLinkInsert.html
<script type="text/javascript">
/////////////// Node /////////////////
class Node{
getData(){
return this.data; }
}
init() {
this.head = new Node("A"); //o primeiro nó chamado cabe?a nó
this.head.prev = null; this.head.next = null;
var nodeB = new Node("B"); nodeB.prev = this.head; nodeB.next =
null; this.head.next = nodeB;
var nodeC = new Node("C"); nodeC.prev = nodeB; nodeC.next = null;
nodeB.next = nodeC;
this.tail = new Node("D"); //o último nó chamado nó da cauda
this.tail.prev = nodeC; this.tail.next = null; nodeC.next = this.tail; }
insert(insertPosition, newNode) {
var p = this.head; var i = 0; // Mova o nó para a posição de inserção
while (p.next != null && i < insertPosition-1) {
p = p.next; i++; }
getHead(){
return this.head; }
}
function print(node) {
var p = node; var end = null; while (p != null) // Imprimir do início
ao fim {
var data = p.getData(); document.write(data + " -> "); end = p; p =
p.next; }
document.write("End <br><br>");
p = end; while (p != null) // Imprimir do final ao início {
var data = p.getData(); document.write(data + " -> "); p = p.prev; }
document.write("Start<br><br>"); }
print(doubleLinkList.getHead());
</script>
Resultado: A -> B -> E -> C -> D -> End D -> C -> E -> B -> A -> Start
4. Exclua o índice = 2 nós.
Crie um arquivo: TestDoubleLinkDelete.html
<script type="text/javascript">
/////////////// Node /////////////////
class Node{
getData(){
return this.data; }
}
init() {
this.head = new Node("A"); //o primeiro nó chamado cabe?a nó
this.head.prev = null; this.head.next = null;
var nodeB = new Node("B"); nodeB.prev = this.head; nodeB.next =
null; this.head.next = nodeB;
var nodeC = new Node("C"); nodeC.prev = nodeB; nodeC.next = null;
nodeB.next = nodeC;
this.tail = new Node("D"); //o último nó chamado nó da cauda
this.tail.prev = nodeC; this.tail.next = null; nodeC.next = this.tail; }
remove(removePosition) {
var p = this.head; var i = 0; // Mova o nó para o nó anterior que deseja
excluir while (p.next != null && i < removePosition - 1) {
p = p.next; i++; }
function print(node) {
var p = node; var end = null; while (p != null) // Imprimir do início
ao fim {
var data = p.getData(); document.write(data + " -> "); end = p; p =
p.next; }
document.write("End <br><br>");
p = end; while (p != null) // Imprimir do final ao início {
var data = p.getData(); document.write(data + " -> "); p = p.prev; }
document.write("Start<br><br>"); }
print(doubleLinkList.getHead());
</script>
UML Diagrama
class Node{
constructor(data, next){
this.data = data; this.next = next; }
getData(){
return this.data; }
}
1. Inicialização de lista vinculada circular unidirecional .
class SingleCircleLink{
init() {
// the first node called head node this.head = new Node("A");
this.head.next = null;
var nodeB = new Node("B"); nodeB.next = null; this.head.next =
nodeB;
var nodeC = new Node("C"); nodeC.next = null; nodeB.next = nodeC;
// the last node called tail node this.tail = new Node("D"); this.tail.next
= this.head; nodeC.next = this.tail; }
}
Navegar na lista de acesso
function print(head) {
var p = head;
do{
var data = p.getData();
document.write(data + " -> ");
p = p.next;
}while(p != head);
<script type="text/javascript">
/////////////// Node /////////////////
class Node{
constructor(data, next){
this.data = data; this.next = next; }
getData(){
return this.data; }
}
getHead(){
return this.head; }
}
function print(head) {
var p = head; do{//Imprimir do início ao fim var data = p.getData();
document.write(data + " -> "); p = p.next; }while(p != head);
var data = p.getData(); document.write(data + "<br><br>"); }
var singleCircleLink = new SingleCircleLink();
singleCircleLink.init();
print(singleCircleLink.getHead());
</script>
getData(){
return this.data; }
}
insert(insertPosition, newNode) {
var p = this.head; var i = 0; while (p.next != null && i <
insertPosition - 1) {
p = p.next; i++; }
newNode.next = p.next; p.next = newNode; }
getHead(){
return this.head; }
}
function print(head) {
var p = head; do{
var data = p.getData(); document.write(data + " -> "); p = p.next;
}while(p != head);
var data = p.getData(); document.write(data + "<br><br>"); }
print(singleCircleLink.getHead());
</script>
getData(){
return this.data; }
}
remove(removePosition) {
var p = this.head; var i = 0; while (p.next != null && i <
removePosition - 1) {
p = p.next; i++; }
var temp = p.next; p.next = p.next.next; temp.next = null; }
getHead(){
return this.head; }
}
function print(head) {
var p = head; do{//Imprimir do início ao fim var data = p.getData();
document.write(data + " -> "); p = p.next; }while(p != head);
var data = p.getData(); document.write(data + "<br><br>"); }
var singleCircleLink = new SingleCircleLink();
singleCircleLink.init();
singleCircleLink.remove(2) // Exclua o nó em índice = 2.
print(singleCircleLink.getHead());
</script>
UML Diagrama
class Node{
constructor(data, prev, next){
this.data = data; this.prev = prev; this.next = next; }
getData(){
return this.data; }
}
1. Inicialização de lista vinculada circular em dois sentidos .
class DoubleCircleLink{
init() {
// o primeiro nó chamado cabe?a nó this.head = new Node("A");
this.head.next = null; this.head.prev = null;
var nodeB = new Node("B"); nodeB.next = null; nodeB.prev =
this.head; this.head.next = nodeB;
var nodeC = new Node("C"); nodeC.next = null; nodeC.prev = nodeB;
nodeB.next = nodeC;
// o último nó chamado nó da cauda this.tail = new Node("D");
this.tail.next = this.head; this.tail.prev = nodeC; nodeC.next = this.tail;
this.head.prev = this.tail; }
}
Navegue na lista ligada: next
Navegue na lista ligada: prev
Crie um arquivo: TestDoubleCircleLink.html
<script type="text/javascript">
/////////////// Node /////////////////
class Node{
constructor(data, prev, next){
this.data = data; this.prev = prev; this.next = next; }
getData(){
return this.data; }
}
/////////////// DoubleCircleLink/////////////////
class DoubleCircleLink{
init() {
// o primeiro nó chamado cabe?a nó this.head = new Node("A");
this.head.next = null; this.head.prev = null;
var nodeB = new Node("B"); nodeB.next = null; nodeB.prev =
this.head; this.head.next = nodeB;
var nodeC = new Node("C"); nodeC.next = null; nodeC.prev = nodeB;
nodeB.next = nodeC;
// o último nó chamado nó da cauda this.tail = new Node("D");
this.tail.next = this.head; this.tail.prev = nodeC; nodeC.next = this.tail;
this.head.prev = this.tail; }
getHead(){
return this.head; }
getTail(){
return this.tail; }
<script type="text/javascript">
/////////////// Node /////////////////
class Node{
constructor(data, prev, next){
this.data = data; this.prev = prev; this.next = next; }
getData(){
return this.data; }
}
/////////////// DoubleCircleLink/////////////////
class DoubleCircleLink{
init() {
// o primeiro nó chamado cabe?a nó this.head = new Node("A");
this.head.next = null; this.head.prev = null;
var nodeB = new Node("B"); nodeB.next = null; nodeB.prev =
this.head; this.head.next = nodeB;
var nodeC = new Node("C"); nodeC.next = null; nodeC.prev = nodeB;
nodeB.next = nodeC;
// o último nó chamado nó da cauda this.tail = new Node("D");
this.tail.next = this.head; this.tail.prev = nodeC; nodeC.next = this.tail;
this.head.prev = this.tail; }
insert(insertPosition, newNode) {
var p = this.head; var i = 0; // Mova o nó para a posição de inserção
while (p.next != null && i < insertPosition - 1) {
p = p.next; i++; }
getHead(){
return this.head; }
getTail(){
return this.tail; }
}
/////////////////// test ////////////////////
function print(head, tail) {
var p = head; do {//Imprimir do início ao fim var data = p.getData();
document.write(data + " -> "); p = p.next; } while (p != head);
var data = p.getData(); document.write(data + "<br><br>");
p = tail; do {//Imprimir do final ao início data = p.getData();
document.write(data + " -> "); p = p.prev; } while (p != tail);
data = p.getData(); document.write(data + "<br><br>"); }
print(doubleCircleLink.getHead(), doubleCircleLink.getTail());
</script>
Resultado: A -> B -> E -> C -> D -> A
D -> C -> E -> B -> A -> D
4. Exclua o índice = 2 nós.
Crie um arquivo: TestDoubleCircleLinkDelete.html
<script type="text/javascript">
/////////////// Node /////////////////
class Node{
constructor(data, prev, next){
this.data = data; this.prev = prev; this.next = next; }
getData(){
return this.data; }
}
/////////////// DoubleCircleLink/////////////////
class DoubleCircleLink{
init() {
// o primeiro nó chamado cabe?a nó this.head = new Node("A");
this.head.next = null; this.head.prev = null;
var nodeB = new Node("B"); nodeB.next = null; nodeB.prev =
this.head; this.head.next = nodeB;
var nodeC = new Node("C"); nodeC.next = null; nodeC.prev = nodeB;
nodeB.next = nodeC;
//o último nó chamado nó da cauda this.tail = new Node("D");
this.tail.next = this.head; this.tail.prev = nodeC; nodeC.next = this.tail;
this.head.prev = this.tail; }
remove(removePosition) {
var p = this.head; var i = 0; while (p.next != null && i <
removePosition - 1) {
p = p.next; i++; }
getHead(){
return this.head; }
getTail(){
return this.tail; }
}
/////////////////// test ////////////////////
function print(head, tail) {
var p = head; do {// Imprimir do início ao fim var data = p.getData();
document.write(data + " -> "); p = p.next; } while (p != head);
var data = p.getData(); document.write(data + "<br><br>");
p = tail; do {// Imprimir do final ao início data = p.getData();
document.write(data + " -> "); p = p.prev; } while (p != tail);
data = p.getData(); document.write(data + "<br><br>"); }
print(doubleCircleLink.getHead(), doubleCircleLink.getTail());
</script>
UML Diagrama
class Node{
constructor(data, prev, next){
this.data = data; this.prev = prev; this.next = next; }
getData(){
return this.data; }
}
1. Inicialização de fila .
Inserir A
Inserir B
Inserir C
Inserir D
Crie um arquivo: TestQueue.html
size() {
return this.size; }
UML Diagrama
class Node{
constructor(data, next){
this.data = data;
this.next = next;
}
getData(){
return this.data;
}
}
1. Inicialização de pilha .
size() {
return this.size; }
}
function print(stack) {
document.write("Top "); var node = null; while ((node =
stack.pop())!=null) {
document.write(node.getData() + " -> "); }
document.write("End <br>"); }
//////////////////////testing////////////////////
//////////////////////testing////////////////////
Resultado:
50,60,70,80,90,100
Algoritmo de mesclagem bidirecional
Algoritmo de mesclagem bidirecional (Two-way Merge Algorithm): Os
dados da primeira metade e da segunda metade são classificados e as duas
sub-listas ordenadas são mescladas em uma lista ordenada, que continua
recursiva até o final.
for (var i = 0; i < elementNumber; i++) {// Copiar temp para array
array[rightEndIndex] = temp[rightEndIndex]; rightEndIndex--; }
}
}
//////////////////////testing////////////////////
var scores = [ 50, 65, 99, 87, 74, 63, 76, 100, 92 ];
var mergeSort = new MergeSort();
mergeSort.sort(scores);
for (var i = 0; i < scores.length; i++) {
document.write(scores[i] + ","); }
</script>
Resultado:
50,63,65,74,76,87,99,100
Árvore de pesquisa binária
Árvore de pesquisa binária (Binary Search Tree): 1. Se a subárvore
esquerda de qualquer nó não estiver vazia, o valor de todos os nós na
subárvore esquerda será menor que o valor do nó raiz; 2. Se a subárvore
direita de qualquer nó não estiver vazia, o valor de todos os nós na
subárvore direita será maior que o valor do nó raiz; 3. A subárvore esquerda
e a subárvore direita de qualquer nó também são árvores de pesquisa
binária.
UML Diagrama
class Node{
constructor(data, left, right){
this.data = data;
this.left = left;
this.right = right;
}
getData(){
return this.data;
}
}
1. Construir uma árvore de pesquisa binária Os nós inseridos são
comparados a partir do nó raiz e o menor que o nó raiz é comparado com a
subárvore esquerda do nó raiz, caso contrário, comparado com a subárvore
direita até que a subárvore esquerda esteja vazia ou a subárvore direita
esteja vazia, será inserido.
Inserir 60
Inserir 40
Inserir 20
Inserir 10
Inserir 30
Inserir 50
Inserir 80
Inserir 70
Inserir 90
2. á rvore de pesquisa binária In-order traversal
In-order traversal : left subtree -> root node -> right subtree
Resultado:
Crie um arquivo: TestBinarySearchTreeInOrder.html
inOrder(root) {
if (root == null) {
return; }
this.inOrder(root.left); // Recursivamente Percorrendo a subárvore
esquerda document.write(root.getData() + ", "); this.inOrder(root.right); //
Recursivamente Percorrendo a subárvore direita }
insert(node, newData) {
if (this.root == null) {
this.root = new Node(newData, null, null); return; }
class Node{
constructor(data, left, right){
this.data = data; this.left = left; this.right = right; }
getData(){
return this.data; }
}
//////////////////////testing////////////////////
Resultado: In-order traversal binary search tree 10, 20, 30, 40, 50, 60, 70,
80, 90,
3. árvore de pesquisa binária Pre-order traversal
Pre-order traversal : root node -> left subtree -> right subtree
Resultado:
Crie um arquivo: TestBinarySearchTreePreOrder.html
preOrder(root) {
if (root == null) {
return; }
document.write(root.getData() + ", "); this.preOrder(root.left); //
Recursivamente Percorrendo a subárvore esquerda
this.preOrder(root.right); // Recursivamente Percorrendo a subárvore
direita }
insert(node, newData) {
if (this.root == null) {
this.root = new Node(newData, null, null); return; }
class Node{
constructor(data, left, right){
this.data = data; this.left = left; this.right = right; }
getData(){
return this.data; }
}
//////////////////////testing////////////////////
Resultado: Pre-order traversal binary search tree 60, 40, 20, 10, 30, 50, 80,
70, 90,
4. á rvore de pesquisa binária Post-order traversal
Post-order traversal : right subtree -> root node -> left subtree
Resultado:
Crie um arquivo: TestBinarySearchTreePostOrder.html
postOrder(root) {
if (root == null) {
return; }
this.postOrder(root.left); // Recursivamente Percorrendo a subárvore
esquerda this.postOrder(root.right); // Recursivamente Percorrendo a
subárvore direita document.write(root.getData() + ", "); }
insert(node, newData) {
if (this.root == null) {
this.root = new Node(newData, null, null); return; }
class Node{
constructor(data, left, right){
this.data = data; this.left = left; this.right = right; }
getData(){
return this.data; }
}
//////////////////////testing////////////////////
Resultado: Post-order traversal binary search tree 10, 30, 20, 50, 40, 70,
90, 80, 60,
5. á rvore de pesquisa binária Máximo e mínimo
Mínimo: O valor pequeno está no nó filho esquerdo, desde que a recursão
atravesse o filho esquerdo até ficar vazio, o nó atual é o nó mínimo.
Máximo: O valor grande está no nó filho certo, desde que o percurso
recursivo seja o filho certo até ficar vazio, o nó atual é o maior nó.
Crie um arquivo: TestBinarySearchTreeMaxMinValue.html
// Minimum searchMinValue(node) {
if (node == null || node.getData() == 0) return null; if (node.left ==
null) {
return node; }
// Encontre recursivamente o mínimo na subárvore esquerda return
this.searchMinValue(node.left); }
// Maximum searchMaxValue(node) {
if (node == null || node.getData() == 0) return null; if (node.right ==
null) {
return node; }
// Encontre recursivamente o valor máximo da subárvore direita return
this.searchMaxValue(node.right); }
insert(node, newData) {
if (this.root == null) {
this.root = new Node(newData, null, null); return; }
var compareValue = newData - node.getData(); // Subárvore esquerda
recursiva, continue a encontrar a posição de inserção if (compareValue <
0) {
if (node.left == null) {
node.left = new Node(newData, null, null); } else {
this.insert(node.left, newData); }
} else if (compareValue > 0) {// Subárvore direita recursiva para
encontrar a posição de inserção if (node.right == null) {
node.right = new Node(newData, null, null); } else {
this.insert(node.right, newData); }
}
}
}
class Node{
constructor(data, left, right){
this.data = data; this.left = left; this.right = right; }
getData(){
return this.data; }
}
//////////////////////testing////////////////////
10
Maximum Value
90
6. árvore de pesquisa binária Delete Node
getData(){
return this.data; }
setData(data){
this.data = data; }
}
class BinaryTree {
getRoot() {
return this.root; }
inOrder(root) {
if (root == null) {
return; }
this.inOrder(root.left); // Recursivamente Percorrendo a subárvore
esquerda document.write(root.getData() + ", "); this.inOrder(root.right); //
Recursivamente Percorrendo a subárvore direita }
searchMinValue(node) {
if (node == null || node.getData() == 0) return null; if (node.left ==
null) {
return node; }
// Encontre recursivamente o mínimo na subárvore esquerda return
this.searchMinValue(node.left); }
remove(node, newData) {
if (node == null) return node; var compareValue = newData -
node.getData(); if (compareValue > 0) {
node.right = this.remove(node.right, newData); } else if (compareValue
< 0) {
node.left = this.remove(node.left, newData); } else if (node.left != null
&& node.right != null) {
// Encontre o nó mínimo da subárvore direita para substituir o nó atual
node.setData(this.searchMinValue(node.right).getData()); node.right =
this.remove(node.right, node.getData()); } else {
node = (node.left != null) ? node.left : node.right; }
return node; }
insert(node, newData) {
if (this.root == null) {
this.root = new Node(newData, null, null); return; }
//////////////////////testing////////////////////
var binaryTree=new BinaryTree(); // Construindo uma árvore de
pesquisa binária binaryTree.insert(binaryTree.getRoot(), 60);
binaryTree.insert(binaryTree.getRoot(), 40);
binaryTree.insert(binaryTree.getRoot(), 20);
binaryTree.insert(binaryTree.getRoot(), 10);
binaryTree.insert(binaryTree.getRoot(), 30);
binaryTree.insert(binaryTree.getRoot(), 50);
binaryTree.insert(binaryTree.getRoot(), 80);
binaryTree.insert(binaryTree.getRoot(), 70);
binaryTree.insert(binaryTree.getRoot(), 90);
document.write("<br>delete node is: 10 <br>");
binaryTree.remove(binaryTree.getRoot(), 10); document.write("<br>In-
order traversal binary tree <br>");
binaryTree.inOrder(binaryTree.getRoot());
document.write("<br>--------------------------------------------<br>");
document.write("<br>delete node is: 20<br>");
binaryTree.remove(binaryTree.getRoot(), 20);
document.write("<br>In-order traversal binary tree<br>");
binaryTree.inOrder(binaryTree.getRoot());
document.write("<br>--------------------------------------------<br>");
document.write("<br>delete node is: 40<br>");
binaryTree.remove(binaryTree.getRoot(), 40);
document.write("<br>In-order traversal binary tree<br>");
binaryTree.inOrder(binaryTree.getRoot()); </script>
Resultado: delete node is: 10
In-order traversal binary tree 20 , 30 , 40 , 50 , 60 , 70 , 80 , 90 , --------------
------------------------------
delete node is: 20
In-order traversal binary tree 30 , 40 , 50 , 60 , 70 , 80 , 90 , -------------------
-------------------------
delete node is: 40
In-order traversal binary tree 30 , 50 , 60 , 70 , 80 , 90 ,
Ordenar da pilha
Ordenar da pilha (Heap Sorting): O valor do nó não terminal na árvore
binária não é maior que o valor de seus nós filhos esquerdo e direito.
Ordenar da pilha:
1. {10, 90, 20, 80, 30, 70, 40, 60, 50} construir heap e, em seguida, heap
classificar saída.
this.array[currentIndex] = noLeafValue; }
heapSort() {
for (var i = this.array.length - 1; i > 0; i--) {
var temp = this.array[0]; this.array[0] = this.array[i]; this.array[i] =
temp; this.adjustHeap(0, i - 1); }
}
}
//////////////////////testing////////////////////
var heapSort = new HeapSort();
var scores = [ 10, 90, 20, 80, 30, 70, 40, 60, 50 ];
document.write("Before building a heap : <br>"); for (var i = 0; i <
scores.length; i++) {
document.write(scores[i] + ", "); }
document.write("<br><br>");
////////////////////////////////////////////////////////////
document.write("After building a heap : <br>");
heapSort.createHeap(scores); for (var i = 0; i < scores.length; i++) {
document.write(scores[i] + ", "); }
document.write("<br><br>");
////////////////////////////////////////////////////////////
document.write("After heap sorting : <br>"); heapSort.heapSort(); for
(var i = 0; i < scores.length; i++) {
document.write(scores[i] + ", "); }
</script>
Resultado: Before building a heap : 10 , 90 , 20 , 80 , 30 , 70 , 40 , 60 , 50 ,
After building a heap : 90 , 80 , 70 , 60 , 30 , 20 , 40 , 10 , 50 ,
After heap sorting : 10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 , 90 ,
Tabela de hash
Tabela de hash (Hash Table): Uma tabela de hash é uma estrutura de
dados que acessa diretamente um local de armazenamento na memória com
base em uma chave. Em outras palavras, ele acessa os registros calculando
uma função nos valores-chave, mapeando os dados a serem consultados
para um local na tabela, o que acelera a pesquisa. Essa função de
mapeamento é chamada de função hash, e a matriz que armazena os
registros é chamada de tabela hash. key => values.
1. Mapeie {19, 18, 35,40,41,42} para a chave da regra de mapeamento
key% 4
2. Hashtable
getKey() {
return this.key; }
setKey(key) {
this.key = key; }
getValue() {
return this.value; }
setValue(value) {
this.value = value; }
getHash() {
return this.hash; }
setHash(hash) {
this.hash = hash; }
}
class Hashtable {
constructor(){
this.capacity = 16; this.table = new Array(this.capacity); this.size = 0; }
size() {
return this.size; }
isEmpty() {
return this.size == 0 ? true : false; }
hash(key) {
var hash = 0; for (var i = 0; i < key.length; i++) {
hash += key.charCodeAt(i); }
return hash % 37; }
get(key) {
if (key == null) {
return null; }
var hash = this.hashCode(key); var node = this.table[hash]; while
(node != null) {// Obter value de acordo com key if (node.getKey() ==
key) {
return node.getValue(); }
node = node.next; }
return null; }
put(key, value) {
if (key == null) {
throw new IllegalArgumentException(); }
//////////////////////testing////////////////////
Resultado: david => Good Boy Keep Going grace => Cute Girl Keep
Going
Gráfico direcionado e pesquisa em
profundidade
Gráfico direcionado (Directed Graph):
A estrutura de dados é representada por uma matriz de adjacência (ou seja,
uma matriz bidimensional) e uma lista de adjacência. Cada nó é chamado
de vértice (vertex) e dois nós adjacentes são chamados de arestas (edge).
1. matriz de adjacência:
O número total de vértices é um tamanho de matriz bidimensional, se
houver aresta de valor 1, caso contrário, aresta é 0.
2. Primeira pesquisa de profundidade:
Procure o nó de borda vizinho B de A e, em seguida, encontre o nó vizinho
C de B e assim por diante até que todos os nós sejam encontrados A -> B ->
C -> D -> E.
Crie um arquivo: TestDirectedGraphDepthFrstSearch.html
getData() {
return this.data; }
setData(data) {
this.data = data; }
isVisited() {
return this.visited; }
setVisited(visited) {
this.visited = visited; }
}
class Stack {
constructor(){
this.stacks = new Array(); this.top = -1; }
push(element) {
this.top++; this.stacks[this.top] = element; }
pop() {
if(this.top == -1){
return -1; }
peek() {
if(this.top == -1){
return -1; }
isEmpty() {
if(this.top <= -1){
return true; }
return false; }
}
class Graph {
constructor(maxVertexSize){
this.maxVertexSize = maxVertexSize;// Tamanho bidimensional da
matriz this.vertexs = new Array(maxVertexSize); this.size = 0; // tamanho
do vértice this.adjacencyMatrix = new Array(maxVertexSize); for (var i
= 0; i < maxVertexSize; i++) {
this.adjacencyMatrix[i] = new Array(); for (var j = 0; j <
maxVertexSize; j++) {
this.adjacencyMatrix[i][j] = 0; }
}
this.stack = new Stack();//salva vértices atuais }
addVertex(data) {
var vertex = new Vertex(data, false); this.vertexs[this.size++] = vertex;
}
addEdge(from, to) {
this.adjacencyMatrix[from][to] = 1; // A -> B e B -> A são diferentes }
depthFirstSearch() {
var firstVertex = this.vertexs[0]; // Comece a pesquisar a partir do
primeiro vértice firstVertex.setVisited(true);
document.write(firstVertex.getData()); this.stack.push(0); while
(!this.stack.isEmpty()) {
var row = this.stack.peek(); // Obter posições de vértice adjacentes que
não foram visitadas var col = this.findAdjacencyUnVisitedVertex(row); if
(col == -1) {
this.stack.pop(); } else {
this.vertexs[col].setVisited(true); document.write(" -> " +
this.vertexs[col].getData()); this.stack.push(col); }
}
this.clear(); }
clear() {
for (var i = 0; i < this.size; i++) {
this.vertexs[i].setVisited(false); }
}
getAdjacencyMatrix() {
return this.adjacencyMatrix; }
getVertexs() {
return this.vertexs; }
}
function printGraph(graph) {
document.write("Two-dimensional array traversal output vertex edge
and adjacent array : <br>"); document.write(" ");
for (var i = 0; i < graph.getVertexs().length; i++) {
document.write(graph.getVertexs()[i].getData() +
" "); }
document.write("<br>");
for (var i = 0; i < graph.getAdjacencyMatrix().length; i++) {
document.write(graph.getVertexs()[i].getData() + " "); for (var j = 0; j
< graph.getAdjacencyMatrix().length; j++) {
document.write(graph.getAdjacencyMatrix()[i][j] +
" "); }
document.write("<br>"); }
}
Resultado:
ABCDE
A01110
B00110
C00010
D00001
E00000
Depth-first search traversal output :A -> B -> C -> D -> E
Gráfico dirigido e Primeira pesquisa
de largura
Primeira pesquisa de largura (Breadth-First Search): Encontre todos os
nós de borda vizinhos B, C, D de A e, em seguida, encontre todos os nós
vizinhos A, C, D de B e assim por diante até que todos os nós sejam
encontrados A -> B -> C -> D -> E.
Crie um arquivo: TestDirectedGraphBreadthFrstSearch.html
getData() {
return this.data; }
setData(data) {
this.data = data; }
isVisited() {
return this.visited; }
setVisited(visited) {
this.visited = visited; }
}
class Queue {
constructor(){
this.queues = new Array(); }
add(element) {
this.queues[this.queues.length] = element; }
remove() {
if(this.queues.length <= 0){
return -1; }
return this.queues.shift(); }
isEmpty() {
if(this.queues.length <= 0){
return true; }
return false; }
}
class Graph {
constructor(maxVertexSize){
this.maxVertexSize = maxVertexSize;// Tamanho bidimensional da
matriz this.vertexs = new Array(maxVertexSize); this.size = 0; // tamanho
do vértice this.adjacencyMatrix = new Array(maxVertexSize); for (var i
= 0; i < maxVertexSize; i++) {
this.adjacencyMatrix[i] = new Array(); for (var j = 0; j <
maxVertexSize; j++) {
this.adjacencyMatrix[i][j] = 0; }
}
this.queue = new Queue();//salva vértices atuais }
addVertex(data) {
var vertex = new Vertex(data, false); this.vertexs[this.size] = vertex;
this.size++; }
addEdge(from, to) {
// A -> B e B -> A são diferentes this.adjacencyMatrix[from][to] = 1; }
getAdjacencyMatrix() {
return this.adjacencyMatrix; }
getVertexs() {
return this.vertexs; }
breadthFirstSearch() {
// Comece a pesquisar a partir do primeiro vértice var firstVertex =
this.vertexs[0]; firstVertex.setVisited(true);
document.write(firstVertex.getData()); this.queue.add(0);
var col = 0; while (!this.queue.isEmpty()) {
var head = this.queue.remove(); // Obter posições de vértice adjacentes
que não foram visitadas col = this.findAdjacencyUnVisitedVertex(head);
// Passa por todos os vértices conectados ao vértice atual while (col !=
-1) {
this.vertexs[col].setVisited(true); document.write(" -> " +
this.vertexs[col].getData()); this.queue.add(col); col =
this.findAdjacencyUnVisitedVertex(head); }
}
this.clear(); }
clear() {
for (var i = 0; i < this.size; i++) {
this.vertexs[i].setVisited(false); }
}
}
function printGraph(graph) {
for (var i = 0; i < graph.getVertexs().length; i++) {
document.write(graph.getVertexs()[i].getData() +
" "); }
document.write("<br>");
for (var i = 0; i < graph.getAdjacencyMatrix().length; i++) {
document.write(graph.getVertexs()[i].getData() + " "); for (var j = 0; j
< graph.getAdjacencyMatrix().length; j++) {
document.write(graph.getAdjacencyMatrix()[i][j] +
" "); }
document.write("<br>"); }
}
ABCDE
A01110
B00110
C00010
D00001
E00000
Breadth-First Search traversal output :A -> B -> C -> D -> E
Ordenar topológica
Ordenar topológica (Topological Sorting): Classifique os vértices no
gráfico direcionado com a ordem de direção .
O gráfico direcionado tem direção : A -> B e B -> A são diferentes
1. matriz de adjacência:
O número total de vértices é um tamanho de matriz bidimensional, se
houver aresta de valor 1, caso contrário, aresta é 0.
Ordenar topológica a partir do vértice A : A -> B -> C -> D -> E
Crie um arquivo: TestTopologicalSorting.html
getData() {
return this.data; }
setData(data) {
this.data = data; }
isVisited() {
return this.visited; }
setVisited(visited) {
this.visited = visited; }
}
class Graph {
constructor(maxVertexSize){
this.maxVertexSize = maxVertexSize;// Tamanho bidimensional da
matriz this.vertexs = new Array(maxVertexSize); this.topologys = new
Array(); this.adjacencyMatrix = new Array(maxVertexSize); for (var i =
0; i < maxVertexSize; i++) {
this.adjacencyMatrix[i] = new Array(); for (var j = 0; j <
maxVertexSize; j++) {
this.adjacencyMatrix[i][j] = 0; }
}
this.size = 0; }
addVertex(data) {
var vertex = new Vertex(data, false); this.vertexs[this.size] = vertex;
this.size++; }
addEdge(from, to) {
// A -> B e B -> A são diferentes this.adjacencyMatrix[from][to] = 1; }
topologySort() {
while (this.size > 0) {
//Obter nó que nenhum nó sucessor var noSuccessorVertex =
this.getNoSuccessorVertex(); if (noSuccessorVertex == -1) {
document.write("There is ring in Graph "); return; }
// Copie o nó excluído para a matriz classificada this.topologys[this.size
- 1] = this.vertexs[noSuccessorVertex]; // Excluir nó que não possui nó
sucessor this.removeVertex(noSuccessorVertex); }
}
getNoSuccessorVertex() {
var existSuccessor = false; for (var row = 0; row < this.size; row++) {
existSuccessor = false; // Se o nó tiver uma linha fixa, cada coluna terá
um 1, indicando que o nó possui um sucessor, finalizando o loop for (var
col = 0; col < this.size; col++) {
if (this.adjacencyMatrix[row][col] == 1) {
existSuccessor = true; break; }
}
removeVertex(vertex) {
if (vertex != this.size - 1) { // Se o vértice é o último elemento, o final //
Os vértices são removidos da matriz de vértices for (var i = vertex; i <
this.size - 1; i++) {
this.vertexs[i] = this.vertexs[i + 1]; }
for (var row = vertex; row < this.size - 1; row++) {// Mover uma linha
para cima for (var col = 0; col < this.size - 1; col++) {
this.adjacencyMatrix[row][col] = this.adjacencyMatrix[row + 1][col]; }
}
for (var col = vertex; col < this.size - 1; col++) {// Mova uma linha
para a esquerda for (var row = 0; row < this.size - 1; row++) {
this.adjacencyMatrix[row][col] = this.adjacencyMatrix[row][col + 1]; }
}
}
this.size--;// Diminuir o número de vértices }
clear() {
for (var i = 0; i < this.size; i++) {
this.vertexs[i].setVisited(false); }
}
getAdjacencyMatrix() {
return this.adjacencyMatrix; }
getVertexs() {
return this.vertexs; }
getTopologys() {
return this.topologys; }
}
//////////////////////testing////////////////////
function printGraph(graph) {
document.write("Two-dimensional array traversal output vertex edge
and adjacent array : <br>"); document.write(" ");
for (var i = 0; i < graph.getVertexs().length; i++) {
document.write(graph.getVertexs()[i].getData() +
" "); }
document.write("<br>");
for (var i = 0; i < graph.getAdjacencyMatrix().length; i++) {
document.write(graph.getVertexs()[i].getData() + " "); for (var j = 0; j
< graph.getAdjacencyMatrix().length; j++) {
document.write(graph.getAdjacencyMatrix()[i][j] +
" "); }
document.write("<br>"); }
}
ABCDE
A01110
B00110
C00010
D00001
E00000
1
Move 1 A to C
2
Move 1 A to B
Move 2 from A to C
Move 1 B to C
Resultado Executar novamente: Please enter the number of discs :
3
Move 1 A to C
Move 2 from A to B
Move 1 C to B
Move 3 from A to C
Move 1 B to A Move 2 from B to C
Move 1 A to C
Fibonacci
Fibonacci : um matemático europeu nos anos 1200, em seus escritos:
"Se houver um coelho Depois de um mês, pode nascer um coelho recém-
nascido. No início havia apenas 1 coelho, após um mês ainda 1 coelho. após
dois meses, 2 coelhos, e após três meses, há 3 coelhos por exemplo: 1, 1, 2,
3, 5, 8, 13 ...
Definição de Fibonacci:
if n = 0, 1
fn = n if n > 1
fn = fn-1 + fn-2
1. Crie um Fibonacci.html com o Bloco de notas e abra-o em seu
navegador.
//////////////////////testing////////////////////
document.write("Please enter the number of month : 7 <br>"); var
number = 7;
for (var i = 1; i <= number; i++) {
document.write(i + " month:" + fibonacci(i) + "<br>"); }
</script>
7
1 month : 1
2 month : 1
3 month : 2
4 month : 3
5 month : 5
6 month : 8
7 month : 13
Dijkstra
A bandeira tricolor foi hasteada originalmente por E.W. Dijkstra, que usava
a bandeira nacional holandesa (Dijkstra é holandesa).
Suponha que haja uma corda com bandeiras vermelha, branca e azul. No
início, todas as bandeiras na corda não estão em ordem. Você precisa
organizá-los na ordem de azul -> branco -> vermelho. Como movê-los com
o mínimo de vezes. você só faz isso na corda e apenas troca duas bandeiras
de cada vez.
//////////////////////testing////////////////////
Resultado:
BBWWRR
The total exchange count : 4
Labirinto de caminhada do rato
(Mouse Walking Maze ) Mouse Walking Maze é um
tipo básico de solução recursiva. Usamos 2 para representar a parede em
uma matriz bidimensional e usamos 1 para representar o caminho do mouse
e tentamos encontrar o caminho da entrada até a saída.
Solução Gráfica
1. Crie um MouseWalkingMaze.html com o Bloco de notas e abra-o em
seu navegador.
<script type="text/javascript">
var maze = [
[ 2, 2, 2, 2, 2, 2, 2 ],
[ 2, 0, 0, 0, 0, 0, 2 ],
[ 2, 2, 2, 0, 2, 0, 2 ],
[ 2, 0, 2, 0, 0, 2, 2 ],
[ 2, 2, 0, 2, 0, 2, 2 ],
[ 2, 0, 0, 0, 0, 0, 2 ],
[ 2, 2, 2, 2, 2, 2, 2 ]
];
var startI = 1;
var startJ = 1;
var endI = 5;
var endJ = 5;
var success = 0;
//////////////////////testing////////////////////
document.write("Maze:<br>");
for (var i = 0; i < 7; i++) {
for (var j = 0; j < 7; j++) {
if (maze[i][j] == 2) {
document.write("█ ");
} else {
document.write("* ");
}
}
document.write("<br>");
}
if (visit(startI, startJ) == 0) {
document.write("No exit found <br>");
} else {
document.write("Maze Path : <br>");
for (var i = 0; i < 7; i++) {
for (var j = 0; j < 7; j++) {
if (maze[i][j] == 2) {
document.write("█ ");
} else if (maze[i][j] == 1) {
document.write("- ");
} else {
document.write("* ");
}
}
document.write("<br>");
}
}
</script>
Resultado:
Maze :
███████
█*****█
███*█*█
█*█**██
██*█*██
█*****█
███████
Maze Path :
███████
█---**█
███-█*█
█*█--██
██*█-██
█***--█
███████
Eight Coins
Existem oito moedas com a mesma aparência, uma é uma moeda falsificada
e o peso da moeda falsificada é diferente da moeda real, mas não se sabe se
a moeda falsificada é mais leve ou mais pesada do que a moeda real. Crie
um algoritmo eficiente para detectar esta moeda falsificada.
Solução: .
Pegue seis a, b, c, d, e, f de oito moedas e coloque três na balança para
comparação. Suponha que a, b, c sejam colocados em um lado e d, e, f
sejam colocados no outro lado.
1.a + b + c> d + e + f 2.a + b + c = d + e + f 3.a + b + c <d + e + f
Se a + b + c> d + e + f, há uma moeda falsa em uma das seis moedas e g, h
são moedas reais. Neste momento, uma moeda pode ser removida de ambos
os lados. Suponha que c e f sejam removidos. Ao mesmo tempo, uma
moeda de cada lado é substituída. Suponha que as moedas b e e sejam
trocadas, e então a segunda comparação. Existem também três
possibilidades:
1. a + e> d + b: a moeda falsa deve ser uma de a, d. contanto que
comparemos uma moeda real h com a, podemos encontrar a
moeda falsa. Se a> h, a é uma moeda falsificada mais pesada; se a
= h, d é uma moeda falsa mais leve.
2. a + e = d + b: a moeda falsa deve ser uma de c, f, e a moeda real h
é comparada com c. Se c> h, c é uma moeda falsificada mais
pesada; se c = h, então f é uma moeda falsa mais leve.
3. a + e <d + b: um de b ou e é uma moeda falsificada. Use também
a moeda real h para comparar com b, se b> h, então b é uma
moeda falsificada mais pesada; se b = h, então e é uma moeda
falsa mais leve;
<script type="text/javascript">
function compare(coins, i, j, k) {//coin[k] true,coin[i]>coin[j]
if (coins[i] > coins[k]) //coin[i]>coin[j]&&coin[i]>coin[k] ----->coin[i]
is a heavy counterfeit coin
document.write("\nCounterfeit currency " + (i + 1) + " is heavier
<br>");
else //coin[j] is a light counterfeit coin
document.write("\nCounterfeit currency " + (j + 1) + " is lighter
<br>");
}
function eightcoins(coins) {
if (coins[0] + coins[1] + coins[2] == coins[3] + coins[4] + coins[5]){
//(a+b+c)==(d+e+f)
if (coins[6] > coins[7]) //g>h?(g>a?g:a):(h>a?h:a)
compare(coins, 6, 7, 0);
else //h>g?(h>a?h:a):(g>a?g:a)
compare(coins, 7, 6, 0);
} else if (coins[0] + coins[1] + coins[2] > coins[3] + coins[4] +
coins[5]){ //(a+b+c)>(d+e+f)
if (coins[0] + coins[3] == coins[1] + coins[4]) //(a+e)==(d+b)
compare(coins, 2, 5, 0);
else if (coins[0] + coins[3] > coins[1] + coins[4]) //(a+e)>(d+b)
compare(coins, 0, 4, 1);
if (coins[0] + coins[3] < coins[1] + coins[4]) //(a+e)<(d+b)
compare(coins, 1, 3, 0);
} else if (coins[0] + coins[1] + coins[2] < coins[3] + coins[4] +
coins[5]) {//(a+b+c)<(d+e+f)
if (coins[0] + coins[3] == coins[1] + coins[4]) //(a+e)>(d+b)
compare(coins, 5, 2, 0);
else if (coins[0] + coins[3] > coins[1] + coins[4]) //(a+e)>(d+b)
compare(coins, 3, 1, 0);
if (coins[0] + coins[3] < coins[1] + coins[4]) //(a+e)<(d+b)
compare(coins, 4, 0, 1);
}
}
//////////////////////testing////////////////////
var coins = new Array();
// O peso inicial da moeda é 10
for (var i = 0; i < 8; i++)
coins[i] = 10;
document.write("<br>");
Resultado:
Primeira corrida de novo:
Enter weight of counterfeit currency (larger or smaller than 10) :
13
Solução: Contanto que a matriz seja tratada como um anel. Preencha uma
contagem para cada área sem dados, até que a contagem chegue a 11 e, a
seguir, liste a matriz do índice 1, você pode saber que cada ordem de
suicídio nesta posição é a posição de Joseph. A posição de 11 pessoas é a
seguinte: 4 10 1 7 5 2 11 9 3 6 8
Pelo exposto, os dois últimos suicidas ficaram na 2ª e 7ª posições. O
anterior Todo mundo morreu, então eles não sabiam que Joseph e seus
amigos não seguiam as regras do jogo.
N = 11; // 11 pessoas M = 3; // Depois que cada número é relatado à terceira
pessoa, a pessoa deve cometer suicídio.
1. Crie um Josephus.html com o Bloco de notas e abra-o em seu
navegador.
//////////////////////testing////////////////////
var man = new Array(); for (var i = 0; i < N; i++) man[i] = 0;
joseph(man);
document.write("\nJoseph sequence:<br>"); for (var i = 0; i < N; i++)
document.write(man[i] + " , "); </script>