├── LICENSE ├── README.md └── src ├── c ├── BubbleSort.cpp ├── BuscaBinariaRecursiva.cpp ├── BuscaSentinela.c ├── fibonacci.cpp ├── hanoi.c └── inverterDigitos.c ├── java ├── BubbleSort │ ├── BidirectionalBubbleSort.java │ ├── BubbleSort.java │ └── RecursiveBubbleSort.java ├── BuscaBinariaRecursiva.java ├── CountingSort.java ├── Fibonacci.java ├── InsertionSortRecursivo.java ├── MergeSort.java ├── Pilha.java ├── QuickSort │ ├── QuickSort.Java │ └── QuickSortMedianOfThree.java ├── SelectionSort.java ├── VetorCircular.java ├── converterBase.java └── inverterDigitos.java ├── javascript ├── Stack.js ├── binary_search.js ├── bubbleSort.js ├── buscaLinearComSentinela.js ├── fibonacci.js ├── insertionSort.js ├── linearSearch.js ├── mergeSort.js └── selectionSort.js └── python ├── MergeSort ├── MergeSort-1.py └── MergeSort-2.py ├── QuickSort ├── median_of_three_quick_sort.py └── simple_quick_sort.py ├── binary_search.py ├── bogo.py ├── bubble_sort.py ├── busca_linear.py ├── busca_recursiva.py ├── busca_todos_matriz.py ├── fibonacci.py ├── in.py ├── insertion_sort.py ├── matriz_transposta.py ├── selection_sort.py ├── slice.py └── split.py /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Kelvin S. do Prado 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ✏️ Algorithms and Data Structures 2 | 3 | Repositório para implementar algoritmos e estrutura de dados 4 | 5 | ## Índice 6 | 7 | - [Algoritmos](#-algoritmos) 8 | - [Implementando funções](#implementando-funções) 9 | - [Geral](#geral) 10 | - [Busca](#busca) 11 | - [Ordenação](#ordenação) 12 | - [Estrutura de dados](#-estrutura-de-dados) 13 | 14 | 15 | ## 📝 Algoritmos 16 | 17 | 18 | ### Implementando funções 19 | 20 | | Algoritmos | Python | Java | C/C++ | Javascript | 21 | |------|-------|------|------|------| 22 | | In | [Python](src/python/in.py) | Java | C/C++ | Javascript | 23 | | Split | [Python](src/python/split.py) | Java | C/C++ | Javascript | 24 | | Slice | [Python](src/python/slice.py) | Java | C/C++ | Javascript | 25 | 26 | 27 | ### Geral 28 | 29 | | Algoritmos | Python | Java | C/C++ | Javascript | 30 | |------|-------|------|------|------| 31 | | [Algoritmo de Dijkstra](https://pt.wikipedia.org/wiki/Algoritmo_de_Dijkstra) | Python | Java | C/C++ | Javascript | 32 | | [Algoritmo de Floyd Warshall](https://pt.wikipedia.org/wiki/Algoritmo_de_Floyd-Warshall) | Python | Java | C/C++ | Javascript | 33 | | [Caixeiro Viajante](https://pt.wikipedia.org/wiki/Problema_do_caixeiro-viajante) | Python | Java | C/C++ | Javascript | 34 | | [Fibonacci](https://pt.wikipedia.org/wiki/Sequ%C3%AAncia_de_Fibonacci) | [Python](src/python/fibonacci.py) | [Java](src/java/Fibonacci.java) |[C/C++](src/c/fibonacci.cpp) | [Javascript](src/javascript/fibonacci.js) | 35 | | [Passeio do cavalo](https://pt.wikipedia.org/wiki/Problema_do_cavalo) | Python | Java | C/C++ | Javascript | 36 | | [Torre de Hanói](https://pt.wikipedia.org/wiki/Torre_de_Han%C3%B3i) | Python | Java | [C/C++](src/c/hanoi.c) | Javascript | 37 | | [converterBase](https://panda.ime.usp.br/pythonds/static/pythonds_pt/03-EDBasicos/08-DecimalParaBinario.html#:~:text=Mas%20como%20podemos%20facilmente%20converter,um%20inteiro%20maior%20de%200.) | Python | [Java](src/java/converterBase.java) | C/C++ | Javascript | 38 | | [inverterDigitos]() | Python | [Java](src/java/inverterDigitos.java) | [C/C++](src/c/inverterDigitos.c) | Javascript 39 | 40 | ### Busca 41 | 42 | | Algoritmos | Python | Java | C/C++ | Javascript | 43 | |------|-------|------|------|------| 44 | |[Busca Linear](https://pt.wikipedia.org/wiki/Busca_linear#:~:text=Na%20%C3%A1rea%20de%20inform%C3%A1tica%2C%20ou,%C3%A9%20linear%2C%20ou%20seja%2C%20cresce)|[Python](src/python/busca_linear.py)| Java | C/C++ | [Javascript](src/javascript/linearSearch.js) | 45 | | [Busca binária](https://pt.wikipedia.org/wiki/Pesquisa_bin%C3%A1ria) | [Python](src/python/binary_search.py) | [Java](src/java/BuscaBinariaRecursiva.java) | [C/C++](src/c/BuscaBinariaRecursiva.cpp) | Javascript | 46 | | [Busca em grafos](https://www.inf.ufsc.br/grafos/represen/busca.html) | Python | Java | C/C++ | Javascript | 47 | | [Busca sequencial](https://pt.wikipedia.org/wiki/Busca_linear) | Python | Java | C/C++ | Javascript | 48 | | [Busca sequencial recursiva](https://pt.wikipedia.org/wiki/Busca_linear) | [Python](src/python/busca_recursiva.py) | Java | C/C++ | Javascript | 49 | | [Busca utilizando sentinela](https://updatedcode.wordpress.com/2015/06/16/busca-sequencial-com-sentinela/) | Python | Java | [C/C++](src/c/BuscaSentinela.c) | [Javascript](src/javascript/buscaLinearComSentinela.js) | 50 | 51 | 52 | 53 | ### Ordenação 54 | 55 | | Algoritmos | Python | Java | C/C++ | Javascript | 56 | |------|-------|------|------|------| 57 | | [Bogo Sort](https://pt.wikipedia.org/wiki/Bogosort) | Python | Java | C/C++ | Javascript | 58 | | [Bubble Sort](https://pt.wikipedia.org/wiki/Bucket_sort) | [Python](src/python/bubble_sort.py) | [Java](src/java/BubbleSort) | [C/C++](src/c/BubbleSort.cpp) | [Javascript](src/javascript/bubbleSort.js) | 59 | | [Bucket Sort](https://pt.wikipedia.org/wiki/Bucket_sort) | Python | Java | C/C++ | Javascript | 60 | | [Counting Sort](https://pt.wikipedia.org/wiki/Counting_sort) | Python | [Java](src/java/CountingSort.java) | C/C++ | Javascript | 61 | | [Insertion Sort](https://pt.wikipedia.org/wiki/Insertion_sort) | Python | [Java](src/java/InsertionSortRecursivo.java) | C/C++ | [Javascript](src/javascript/insertionSort.js) | 62 | | [Quick Sort](https://pt.wikipedia.org/wiki/Quicksort) | [Python](src/python/QuickSort) | [Java](src/java/QuickSort) | C/C++ | Javascript | 63 | | [Merge Sort](https://pt.wikipedia.org/wiki/Merge_sort) | [Python](src/python/MergeSort) | [Java](src/java/MergeSort.java) | C/C++ | [Javascript](src/javascript/mergeSort.js) | 64 | | [Selection Sort](https://pt.wikipedia.org/wiki/Selection_sort) | [Python](src/python/selection_sort.py) | [Java](src/java/SelectionSort.java) | C/C++ | [Javascript](src/javascript/selectionSort.js) | 65 | 66 | 67 | 68 | 69 | 70 | ## 📝 Estrutura de dados 71 | 72 | | Estrutura de dados | Python | Java | C/C++ | Javascript | 73 | |------|-------|------|------|------| 74 | | [Grafo](https://pt.wikipedia.org/wiki/Teoria_dos_grafos) | Python | Java | C/C++ | Javascript | 75 | | [Pilha](https://pt.wikipedia.org/wiki/LIFO) | Python | [Java](src/java/Pilha.java) | C/C++ | Javascript | 76 | | [Fila circular](https://www.devmedia.com.br/fila-circular-dinamica/24572) | Python | [Java](src/java/VetorCircular.java) | C/C++ | Javascript | 77 | -------------------------------------------------------------------------------- /src/c/BubbleSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | void swap(int vector[], int i, int j){ 7 | int temp = vector[i]; 8 | vector[i] = vector[j]; 9 | vector[j] = temp; 10 | } 11 | 12 | void bubbleSort(int vector[], int leftIndex, int rightIndex){ 13 | for (int i = rightIndex; i > leftIndex; i--) 14 | for (int j = leftIndex; j < i; j++) 15 | if (vector[j] > vector[j+1]) 16 | swap(vector, j, j+1); 17 | } 18 | 19 | void bubbleSort(int vector[], int n){ 20 | bubbleSort(vector, 0, n-1); 21 | } 22 | 23 | void printArray(int arr[], int n){ 24 | cout << "["; 25 | int i; 26 | for (i = 0; i < n; i++) 27 | if (i == n-1) 28 | cout << arr[i]; 29 | else 30 | cout << arr[i] << " "; 31 | cout << "]" << endl; 32 | } 33 | 34 | int main(){ 35 | int array[] = {64, 34, 25, 12, 22, 11, 90}; 36 | int n = sizeof(array) / sizeof(int); 37 | 38 | cout << "Array antes do sort: "; 39 | printArray(array, n); 40 | 41 | bubbleSort(array, 0, 3); 42 | cout << "Array depois do sort: "; 43 | printArray(array, n); 44 | } 45 | -------------------------------------------------------------------------------- /src/c/BuscaBinariaRecursiva.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int buscaBinariaRecursiva(int vector[], int left, int right, int element){ 7 | 8 | int middle = (left + right) / 2; 9 | 10 | if (left > right) 11 | return -1; 12 | 13 | if (vector[middle] == element) 14 | return middle; 15 | 16 | else if (vector[middle] > element) 17 | return buscaBinariaRecursiva(vector, left, middle-1, element); 18 | 19 | else 20 | return buscaBinariaRecursiva(vector, middle+1, right, element); 21 | } 22 | 23 | int buscaBinariaRecursiva(int vector[], int sizeVector, int element){ 24 | return buscaBinariaRecursiva(vector, 0, sizeVector-1, element); 25 | } 26 | 27 | 28 | int main(){ 29 | int arr[] = { 2, 3, 4, 10, 40 }; 30 | int x; 31 | cout << "Element to be searched in the vector: "; 32 | cin >> x; 33 | 34 | int size = sizeof(arr) / sizeof(int); 35 | 36 | int result = buscaBinariaRecursiva(arr, size, x); 37 | 38 | (result == -1) ? cout << "Element is not present in array" << endl 39 | : cout << "Element is present at index " << result << endl; 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /src/c/BuscaSentinela.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Encontra um valor em um vetor sem precisar testar todos os valores dentro do laço 3 | */ 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | #define TAM_VETOR 10 10 | 11 | int buscaSentinela(int vetor[], int chave){ 12 | vetor[TAM_VETOR] = chave; // Coloca o valor buscado (chave) na última posição do vetor 13 | int aux = 0; // Variável de controle do laço 14 | while( vetor[aux] != chave ) // Enquanto não encontrar o valor (chave) incrementa 1 em aux 15 | aux++; 16 | if( aux == TAM_VETOR ) // Caso o valor de aux seja igual ao tamanho do vetor, significa que foi até o final e não encontrou o valor 17 | return -1; // Não encontrou 18 | else // Caso aux seja diferente, significa que encontrou o valor e quebrou o laço, o aux é a posição do valor buscado 19 | return aux; // Encontrou 20 | } 21 | 22 | int main(){ 23 | 24 | int vetor[TAM_VETOR+1]; // Declara o vetor com +1 pois é a posição que será utilizada pelo sentinela 25 | 26 | // Preenche o vetor com valores aleatórios 0-1000 27 | srand(time(NULL)); 28 | for(int i = 0; i < TAM_VETOR; i++){ 29 | vetor[i] = rand()%1000; 30 | printf("%d, ", vetor[i]); 31 | } 32 | 33 | // Faz a busca, passando como parâmetro o vetor e a chave que deseja buscar 34 | int res = buscaSentinela(vetor, vetor[TAM_VETOR-2]); 35 | if( res != -1 ) 36 | printf("\n\nValor %d encontrado na posicao %d.\n\n", vetor[res], res); 37 | else 38 | printf("\n\nValor não encontrado no vetor\n\n"); 39 | 40 | return 0; 41 | } -------------------------------------------------------------------------------- /src/c/fibonacci.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int qtdTermos = 10, termo01 = 0, termo02 = 1; 8 | cout << "Primeiros " << qtdTermos <<" termos: "< 2 | 3 | void hanoi(int discos, int O, int D, int A) { 4 | if (discos == 1) { 5 | printf("(%c,%c)\n", O, D); 6 | return; 7 | } 8 | 9 | // origem -> auxiliar 10 | hanoi(discos - 1, O, A, D); 11 | 12 | // origem -> destino 13 | printf("(%c,%c)\n", O, D); 14 | 15 | // auxiliar -> destino, origem(auxiliar) 16 | hanoi(discos - 1, A, D, O); 17 | } 18 | 19 | int main() { 20 | int entrada; 21 | 22 | printf("Utilizando 3 pinos O, D, A (origem, destino, auxiliar) quantos discos deseja utilizar ? "); 23 | scanf("%d", &entrada); 24 | hanoi(entrada, 'O', 'D', 'A'); 25 | 26 | return 0; 27 | } -------------------------------------------------------------------------------- /src/c/inverterDigitos.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | unsigned long int reverso(unsigned long int n) { 4 | unsigned long int aux, mult, rev; 5 | 6 | aux = n; 7 | mult = 1; 8 | while (aux >= 10) { 9 | aux /= 10; 10 | mult *= 10; 11 | } 12 | aux = n; 13 | rev = 0; 14 | 15 | while (mult > 0) { 16 | rev += (aux % 10) * mult; 17 | aux /= 10; 18 | mult /= 10; 19 | } 20 | return rev; 21 | } 22 | 23 | int main() { 24 | unsigned long int num; 25 | 26 | printf("Digite o número (inteiro positivo) que deseja inverter: "); 27 | scanf("%lu", &num); 28 | printf("%lu\n", reverso(num)); 29 | 30 | return 0; 31 | } -------------------------------------------------------------------------------- /src/java/BubbleSort/BidirectionalBubbleSort.java: -------------------------------------------------------------------------------- 1 | package src.java; 2 | 3 | 4 | /** 5 | * This bubble sort variation has two internal iterations. In the first, it 6 | * pushes big elements to the right, like the normal bubble sort does. Then in 7 | * the second, iterates the array backwards, that is, from right to left, while 8 | * pushing small elements to the left. This process is repeated until the array 9 | * is sorted. 10 | */ 11 | public class BidirectionalBubbleSort{ 12 | 13 | 14 | public void BidirectionalBubblesort(int[] array, int leftIndex, int rightIndex) { 15 | 16 | if( (leftIndex < rightIndex) && (array.length) > 1 && (validIndexes(array, leftIndex,rightIndex)) ) { 17 | 18 | boolean houveTroca = true; 19 | 20 | int left = leftIndex; 21 | int right = rightIndex; 22 | 23 | while(houveTroca) { 24 | 25 | houveTroca = false; 26 | 27 | for( int i = left; i < rightIndex; i++ ) { 28 | 29 | if(array[i+1] < array[i]) { 30 | swap(array, i, i+1); 31 | houveTroca = true; 32 | } 33 | 34 | } 35 | 36 | right --; 37 | 38 | for(int j = right; j > left ; j --) { 39 | 40 | if(array[j-1] > array[j]) { 41 | swap(array, j-1, j); 42 | houveTroca = true; 43 | } 44 | } 45 | 46 | 47 | left ++; 48 | 49 | } 50 | 51 | } else { 52 | return; 53 | } 54 | 55 | } 56 | 57 | private boolean validIndexes(int[] array, int leftIndex, int rightIndex) { 58 | boolean result = true; 59 | 60 | 61 | if( leftIndex >= array.length || leftIndex > rightIndex || leftIndex < 0) { 62 | result = false; 63 | } 64 | 65 | else if(rightIndex >= array.length || rightIndex < 0) { 66 | result = false; 67 | } 68 | 69 | return result; 70 | } 71 | 72 | 73 | public static void swap(int[] array, int i, int j) { 74 | if (array == null) 75 | throw new IllegalArgumentException(); 76 | 77 | int temp = array[i]; 78 | array[i] = array[j]; 79 | array[j] = temp; 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /src/java/BubbleSort/BubbleSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class BubbleSort{ 4 | public static int[] bubbleSort(int [] array){ 5 | for (int i= 0; i < array.length; i++){ 6 | for (int j= i + 1; j < array.length; j++){ 7 | if (array[i] > array[j]){ 8 | int aux = array[i]; 9 | array[i] = array[j]; 10 | array[j] = aux; 11 | } 12 | } 13 | } 14 | return array; 15 | } 16 | 17 | 18 | public static void main(String[] args) { 19 | int [] array = {9,8,7,6,5,4,3,2,1,0}; 20 | System.out.print("This is the ordered array: "); 21 | System.out.println(Arrays.toString(bubbleSort(array))); 22 | } 23 | } -------------------------------------------------------------------------------- /src/java/BubbleSort/RecursiveBubbleSort.java: -------------------------------------------------------------------------------- 1 | package src.java; 2 | 3 | 4 | 5 | public class RecursiveBubbleSort{ 6 | 7 | /** 8 | * Implementação recursiva do bubble sort. Você deve implementar apenas esse 9 | * método sem usar nenhum outro método auxiliar (exceto 10 | * Util.swap(array,int,int)). Para isso, tente definir o caso base do 11 | * algoritmo e depois o caso indutivo, que reduz o problema para uma entrada 12 | * menor em uma chamada recursiva. Seu algoritmo deve ter complexidade 13 | * quadrática O(n^2). 14 | */ 15 | 16 | 17 | public void recursiveBubblesort(int[] array, int leftIndex, int rightIndex) { 18 | 19 | if( (leftIndex < rightIndex) && (array.length) > 1 && (validIndexes(array, leftIndex,rightIndex)) ) { 20 | for(int j = leftIndex; j < rightIndex; j++) { 21 | 22 | if(array[j+1] < array[j]){ 23 | swap(array, j+1, j); 24 | } 25 | } 26 | } 27 | else { 28 | return; 29 | } 30 | 31 | recursiveBubblesort(array, leftIndex, rightIndex - 1); 32 | } 33 | 34 | private boolean validIndexes(int[] array, int leftIndex, int rightIndex) { 35 | boolean result = true; 36 | 37 | 38 | if( leftIndex >= array.length || leftIndex > rightIndex || leftIndex < 0) { 39 | result = false; 40 | } 41 | 42 | else if(rightIndex >= array.length || rightIndex < 0) { 43 | result = false; 44 | } 45 | 46 | return result; 47 | } 48 | 49 | private static void swap(int[] array, int i, int j) { 50 | if (array == null) 51 | throw new IllegalArgumentException(); 52 | 53 | int temp = array[i]; 54 | array[i] = array[j]; 55 | array[j] = temp; 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/java/BuscaBinariaRecursiva.java: -------------------------------------------------------------------------------- 1 | 2 | class BuscaBinariaRecursiva { 3 | 4 | public static int buscaBinariaRecursiva(int[] array, int elemento) { 5 | return buscaBinariaRecursiva(array, 0, array.length - 1, elemento); 6 | } 7 | 8 | public static int buscaBinariaRecursiva(int[] array, int esquerda, int direita, int elemento) { 9 | int centrao = (esquerda + direita) / 2; 10 | 11 | if (esquerda > direita) { 12 | return -1; 13 | } 14 | 15 | if (array[centrao] == elemento) { 16 | return centrao; 17 | } 18 | 19 | else if (array[centrao] < elemento) { 20 | return buscaBinariaRecursiva(array, centrao + 1, direita, elemento); 21 | } 22 | 23 | else { 24 | return buscaBinariaRecursiva(array, esquerda, centrao - 1, elemento); 25 | } 26 | 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/java/CountingSort.java: -------------------------------------------------------------------------------- 1 | package src.java; 2 | 3 | import src.java.*; 4 | 5 | 6 | /** 7 | * Classe que implementa a estratégia de Counting Sort vista em sala. Procure 8 | * evitar desperdicio de memoria alocando o array de contadores com o tamanho 9 | * sendo o máximo inteiro presente no array a ser ordenado. 10 | * 11 | * Voce pode assumir que o maior inteiro armazenado não chega a 100. 12 | * 13 | */ 14 | public class CountingSort{ 15 | 16 | 17 | public void sort(int[] array, int leftIndex, int rightIndex) { 18 | if( (leftIndex < rightIndex) && (array.length) > 1 && (validIndexes(array, leftIndex,rightIndex)) ) { 19 | 20 | int k = findHighestValue(array, leftIndex, rightIndex); 21 | 22 | countingSort(array, k , leftIndex, rightIndex); 23 | 24 | } 25 | 26 | else { 27 | return; 28 | } 29 | } 30 | 31 | 32 | 33 | 34 | private int findHighestValue(int[] array, int leftIndex, int rightIndex) { 35 | 36 | int k = array[leftIndex]; 37 | 38 | for(int i = leftIndex + 1; i <= rightIndex; i++) { 39 | 40 | if(array[i] > k){ 41 | k = array[i]; 42 | } 43 | } 44 | 45 | return k; 46 | } 47 | 48 | 49 | 50 | 51 | private void countingSort(int[] initialArray, int k, int leftIndex, int rightIndex) { 52 | 53 | int[] countingArray = new int[k + 1]; 54 | Arrays.fill(countingArray, 0); 55 | 56 | // frequencia 57 | for(int i = leftIndex; i <= rightIndex; i++) { 58 | countingArray[initialArray[i]] += 1; 59 | } 60 | 61 | // cumulativa 62 | 63 | for(int i = 0; i < countingArray.length - 1; i++) { 64 | 65 | countingArray[i+1] += countingArray[i]; 66 | 67 | } 68 | 69 | int[] orderedArray = new int[rightIndex - leftIndex + 1]; 70 | 71 | for(int i = rightIndex; i >= leftIndex; i--){ 72 | 73 | countingArray[initialArray[i]] -= 1; 74 | 75 | orderedArray[countingArray[initialArray[i]]] = initialArray[i]; 76 | 77 | } 78 | 79 | for(int i = leftIndex; i <= rightIndex; i++){ 80 | initialArray[i] = orderedArray[i-leftIndex]; 81 | 82 | } 83 | 84 | } 85 | 86 | 87 | private boolean validIndexes(int[] array, int leftIndex, int rightIndex) { 88 | boolean result = true; 89 | 90 | 91 | if( leftIndex >= array.length || leftIndex > rightIndex || leftIndex < 0) { 92 | result = false; 93 | } 94 | 95 | else if(rightIndex >= array.length || rightIndex < 0) { 96 | result = false; 97 | } 98 | 99 | return result; 100 | } 101 | 102 | } 103 | -------------------------------------------------------------------------------- /src/java/Fibonacci.java: -------------------------------------------------------------------------------- 1 | public class Fibonacci { 2 | 3 | public static void main(String[] args) { 4 | 5 | int n = 10, t1 = 0, t2 = 1; 6 | System.out.print("First " + n + " terms: "); 7 | 8 | for (int i = 1; i <= n; ++i) 9 | { 10 | System.out.print(t1 + " + "); 11 | 12 | int sum = t1 + t2; 13 | t1 = t2; 14 | t2 = sum; 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/java/InsertionSortRecursivo.java: -------------------------------------------------------------------------------- 1 | class InsertionSortRecursivo { 2 | 3 | public void insertionSortRecursivo(int[] array) { 4 | insertionSortRecursivo(array, 1, array.length); 5 | } 6 | 7 | public void insertionSortRecursivo(int[] array, int inicio, int fim) { 8 | 9 | if (inicio != fim) { 10 | 11 | int j = inicio; 12 | 13 | while (j > 0 && array[j] < array[j - 1]) { 14 | swap(array, j, j - 1); 15 | j -= 1; 16 | } 17 | 18 | insertionSortRecursivo(array, inicio + 1, fim); 19 | } 20 | } 21 | 22 | static void swap(int[] array, int i, int j) { 23 | int aux = array[i]; 24 | array[i] = array[j]; 25 | array[j] = aux; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/java/MergeSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.Arrays; 3 | 4 | public class MergeSort { 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | String[] entrada = sc.nextLine().split(" "); 8 | 9 | int[] numeros = new int[entrada.length]; 10 | 11 | for (int i = 0; i < numeros.length; i++) { 12 | numeros[i] = Integer.parseInt(entrada[i]); 13 | } 14 | 15 | sort(numeros, 0, numeros.length - 1); 16 | 17 | System.out.println("Here's your sorted array: " + Arrays.toString(numeros)); 18 | } 19 | 20 | public static void sort(int[] array, int leftIndex, int rightIndex) { 21 | if(validate(array, leftIndex, rightIndex)) { 22 | if (leftIndex < rightIndex) { 23 | int middle = (leftIndex + rightIndex) / 2; 24 | 25 | sort(array, leftIndex, middle); 26 | sort(array, middle + 1, rightIndex); 27 | 28 | merge(array, leftIndex, rightIndex); 29 | } 30 | } 31 | } 32 | 33 | private static void merge(int[] array, int leftIndex, int rightIndex) { 34 | int[] arrayAux = Arrays.copyOf(array, array.length); 35 | 36 | int start = leftIndex; 37 | int middle = (leftIndex + rightIndex) / 2; 38 | int secStart = middle + 1; 39 | int count = leftIndex; 40 | 41 | while (start <= middle && secStart <= rightIndex) { 42 | if (arrayAux[start] <= arrayAux[secStart]) { 43 | array[count++] = arrayAux[start++]; 44 | } else { 45 | array[count++] = arrayAux[secStart++]; 46 | } 47 | } 48 | 49 | while (start <= middle) { 50 | array[count++] = arrayAux[start++]; 51 | } 52 | 53 | while (secStart <= rightIndex) { 54 | array[count++] = arrayAux[secStart++]; 55 | } 56 | } 57 | 58 | private static boolean validate(int[] array, int leftIndex, int rightIndex) { 59 | return (array != null && leftIndex >= 0 && rightIndex <= array.length - 1 60 | && array.length > 1); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/java/Pilha.java: -------------------------------------------------------------------------------- 1 | package pilha; 2 | 3 | public class Pilha { 4 | 5 | public Object[] pilha; 6 | public int posicaoPilha; 7 | 8 | public Pilha() { 9 | this.posicaoPilha = -1; 10 | // indica que esta nula, vazia, pois posição um indica que contém informação 11 | this.pilha = new Object[1000]; 12 | // criando uma pilha com 1000 posições 13 | } 14 | 15 | public boolean pilhaVazia() { 16 | //isEmpty 17 | if (this.posicaoPilha == -1) { 18 | return true; 19 | } 20 | return false; 21 | } 22 | 23 | public int tamanho() { 24 | //is 25 | if (this.pilhaVazia()) { 26 | return 0; 27 | } 28 | return this.posicaoPilha + 1; 29 | } 30 | 31 | public Object exibeUltimoValor() { 32 | //top 33 | if (this.pilhaVazia()) { 34 | return null; 35 | } 36 | return this.pilha[this.posicaoPilha]; 37 | } 38 | 39 | public Object desempilhar() { 40 | //pop 41 | if (pilhaVazia()) { 42 | return null; 43 | } 44 | return this.pilha[this.posicaoPilha--]; 45 | } 46 | 47 | public void empilhar(Object valor) { 48 | // push 49 | if (this.posicaoPilha < this.pilha.length - 1) { 50 | this.pilha[++posicaoPilha] = valor; 51 | } 52 | } 53 | 54 | public static void main(String args[]) { 55 | Pilha p = new Pilha(); 56 | p.empilhar("Portuguesa "); 57 | p.empilhar("Frango com catupiry "); 58 | p.empilhar("Calabresa "); 59 | p.empilhar("Quatro queijos "); 60 | p.empilhar(10); 61 | 62 | //Listar a pilha 63 | while (p.pilhaVazia() == false) { 64 | System.out.println(p.desempilhar()); 65 | } 66 | } 67 | } -------------------------------------------------------------------------------- /src/java/QuickSort/QuickSort.Java: -------------------------------------------------------------------------------- 1 | 2 | public class QuickSort { 3 | 4 | public void quickSort(int[] array, int leftIndex, int rightIndex) { 5 | 6 | // RightIndex = array.length - 1 7 | 8 | if (leftIndex < rightIndex) { 9 | int indice_do_pivot = particiona(array, leftIndex, rightIndex); 10 | 11 | quickSort(array, leftIndex, indice_do_pivot - 1); 12 | quickSort(array, indice_do_pivot + 1, rightIndex); 13 | } 14 | } 15 | 16 | public int particiona(int[] array, int leftIndex, int rightIndex) { 17 | 18 | int pivot = array[leftIndex]; 19 | int i = leftIndex; 20 | 21 | for (int j = leftIndex + 1; j <= rightIndex; j++) { 22 | if (array[j] < pivot) { 23 | i++; 24 | swap(array, i, j); 25 | } 26 | } 27 | 28 | swap(array, leftIndex, i); 29 | return i; 30 | } 31 | 32 | public void swap(int[] array, int i, int j) { 33 | int aux = array[i]; 34 | array[i] = array[j]; 35 | array[j] = aux; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/java/QuickSort/QuickSortMedianOfThree.java: -------------------------------------------------------------------------------- 1 | package src.java; 2 | 3 | 4 | 5 | 6 | /** 7 | * A classe QuickSortMedianOfThree representa uma variação do QuickSort que 8 | * funciona de forma ligeiramente diferente. Relembre que quando o pivô 9 | * escolhido divide o array aproximadamente na metade, o QuickSort tem um 10 | * desempenho perto do ótimo. Para aproximar a entrada do caso ótimo, diversas 11 | * abordagens podem ser utilizadas. Uma delas é usar a mediana de 3 para achar o 12 | * pivô. Essa técnica consiste no seguinte: 13 | * 1. Comparar o elemento mais a esquerda, o central e o mais a direita do intervalo. 14 | * 2. Ordenar os elementos, tal que: A[left] < A[center] < A[right]. 15 | * 3. Adotar o A[center] como pivô. 16 | * 4. Colocar o pivô na penúltima posição A[right-1]. 17 | * 5. Aplicar o particionamento considerando o vetor menor, de A[left+1] até A[right-1]. 18 | * 6. Aplicar o algoritmo na particao a esquerda e na particao a direita do pivô. 19 | * @param 20 | */ 21 | public class QuickSortMedianOfThree{ 22 | 23 | 24 | public void sort(int[] array, int leftIndex, int rightIndex) { 25 | 26 | if( (leftIndex < rightIndex) && (array.length) > 1 && (validIndexes(array, leftIndex,rightIndex)) ) { 27 | 28 | int indexPivot = partition(array, leftIndex, rightIndex); 29 | 30 | sort(array, leftIndex, indexPivot - 1); 31 | sort(array, indexPivot + 1, rightIndex); 32 | } 33 | else { 34 | return; 35 | } 36 | } 37 | 38 | 39 | private int partition(int[] array, int leftIndex, int rightIndex) { 40 | 41 | 42 | int medianOfThreePivotIndex = pickPivotIndex(array, leftIndex, rightIndex); 43 | 44 | swap(array, leftIndex, medianOfThreePivotIndex); 45 | 46 | int pivot = array[leftIndex]; 47 | int i = leftIndex; 48 | 49 | for(int j = leftIndex + 1; j <= rightIndex; j++){ 50 | if(array[j] <= (pivot) ) { 51 | i++; 52 | swap(array, i, j); 53 | } 54 | } 55 | 56 | swap(array, leftIndex, i); 57 | 58 | 59 | return i; 60 | } 61 | 62 | 63 | 64 | private int pickPivotIndex(int[] array, int leftIndex, int rightIndex) { 65 | 66 | int middleIndex = (leftIndex + rightIndex) / 2; 67 | 68 | if(array[leftIndex] > (array[middleIndex]) ) { 69 | swap(array, leftIndex, middleIndex); 70 | } 71 | 72 | if(array[leftIndex] > (array[rightIndex]) ) { 73 | swap(array, leftIndex, rightIndex); 74 | } 75 | 76 | if(array[middleIndex] > (array[rightIndex]) ) { 77 | swap(array, middleIndex, rightIndex); 78 | } 79 | 80 | return middleIndex; 81 | } 82 | 83 | 84 | private boolean validIndexes(int[] array, int leftIndex, int rightIndex) { 85 | boolean result = true; 86 | 87 | 88 | if( leftIndex >= array.length || leftIndex > rightIndex || leftIndex < 0) { 89 | result = false; 90 | } 91 | 92 | else if(rightIndex >= array.length || rightIndex < 0) { 93 | result = false; 94 | } 95 | 96 | return result; 97 | } 98 | 99 | 100 | private static void swap(int[] array, int i, int j) { 101 | if (array == null) 102 | throw new IllegalArgumentException(); 103 | 104 | int temp = array[i]; 105 | array[i] = array[j]; 106 | array[j] = temp; 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/java/SelectionSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Scanner; 3 | import java.lang.*; 4 | 5 | class SelectionSort { 6 | public static void main(String[] args) { 7 | Scanner entrada = new Scanner(System.in); 8 | String[] numeros = entrada.nextLine().split(" "); 9 | 10 | int[] array = new int[numeros.length]; 11 | 12 | for (int i = 0; i < array.length; i++) { 13 | array[i] = Integer.parseInt(numeros[i]); 14 | } 15 | 16 | selectionSort(array); 17 | 18 | } 19 | 20 | public static void selectionSort(int[] array) { 21 | for (int i = 0; i < array.length; i++) { 22 | int i_menor = i; 23 | for (int j = i_menor + 1; j < array.length; j++) { 24 | if(array[j] < array[i_menor]) { 25 | i_menor = j; 26 | } 27 | } 28 | int aux = array[i]; 29 | array[i] = array[i_menor]; 30 | array[i_menor] = aux; 31 | 32 | 33 | if(i_menor != i) { 34 | System.out.println(Arrays.toString(array)); 35 | } 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /src/java/VetorCircular.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class VetorCircular { 4 | public static void main(String[] args) { 5 | Scanner input = new Scanner(System.in); 6 | 7 | String[] listaEntrada = input.nextLine().split(" "); 8 | int quantidadeElementos = input.nextInt(); 9 | 10 | int[] arrayInteiros = new int[listaEntrada.length]; 11 | for (int i = 0; i < listaEntrada.length; i++) { 12 | arrayInteiros[i] = Integer.parseInt(listaEntrada[i]); 13 | } 14 | System.out.print(vetorCircular(arrayInteiros, quantidadeElementos)); 15 | } 16 | 17 | private static String vetorCircular(int[] vetor, int quantidadeElementos) { 18 | String saida = ""; 19 | int tamanho = 0; 20 | int indice = 0; 21 | while (tamanho < quantidadeElementos) { 22 | if(indice == vetor.length - 1) { 23 | saida += vetor[indice] + " "; 24 | indice = 0; 25 | } 26 | saida += vetor[indice] + " "; 27 | tamanho = saida.replace(" ", "").length(); 28 | indice++; 29 | } 30 | saida = saida.substring(0,saida.length() - 1); 31 | return saida; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/java/converterBase.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class converterBase { 4 | public static void main(String[] args) { 5 | Scanner prompt = new Scanner(System.in); 6 | int n; 7 | int q; 8 | int ndigit = 0; 9 | int[] novarep = new int[10]; 10 | int r; 11 | public void convert() { 12 | System.out.println("digite um numero"); 13 | n = prompt.nextInt(); 14 | q = n; 15 | do { 16 | r = q % 2; 17 | novarep[ndigit] = r; 18 | ndigit++; 19 | q = q / 2; 20 | } 21 | while (q != 0); { 22 | System.out.println("numero " + n + " na base binaria: "); 23 | for(int i = ndigit - 1; i >= 0; i--) { 24 | System.out.print(novarep[i]); 25 | } 26 | } 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /src/java/inverterDigitos.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class inverterDigitos { 4 | public static void main(String[] args) { 5 | int n; 6 | int inverso = 0; 7 | int digito; 8 | Scanner prompt = new Scanner(System.in); 9 | 10 | public void inverter() { 11 | System.out.println("Numero inteiro positivo: "); 12 | n = prompt.nextInt(); 13 | 14 | while (n > 0) { 15 | digito = n % 10; 16 | inverso = inverso * 10 + digito; 17 | n = n / 10; 18 | } 19 | System.out.println("numero inverso: " + inverso); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /src/javascript/Stack.js: -------------------------------------------------------------------------------- 1 | class Stack { 2 | constructor() { 3 | this.items = []; 4 | } 5 | 6 | push(element) { 7 | this.items[this.items.length] = element; 8 | } 9 | 10 | pop() { 11 | if(this.isEmpty()) { 12 | throw Error("StackUnderflow"); 13 | } 14 | return this.items.pop(); 15 | } 16 | 17 | peek() { 18 | return this.items[this.items.length - 1]; 19 | } 20 | 21 | isEmpty() { 22 | return this.items.length === 0; 23 | } 24 | } -------------------------------------------------------------------------------- /src/javascript/binary_search.js: -------------------------------------------------------------------------------- 1 | function binarySearch(vetor, item, lPointer, rPointer) { 2 | let middleIndex = parseInt((lPointer + rPointer) / 2); 3 | let middleItem = vetor[middleIndex]; 4 | 5 | if (vetor.length !== 0) { 6 | if (item < middleItem) { 7 | rPointer = middleIndex - 1; 8 | middleIndex = binarySearch(vetor, item, lPointer, rPointer) 9 | } 10 | 11 | else if (item > middleItem) { 12 | lPointer = middleIndex + 1; 13 | middleIndex = binarySearch(vetor, item, lPointer, rPointer) 14 | } 15 | 16 | return middleIndex; 17 | } 18 | 19 | else { 20 | console.log('Vetor vazio') 21 | return -1 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/javascript/bubbleSort.js: -------------------------------------------------------------------------------- 1 | function swap(array, i, j) { 2 | let temp = array[i] 3 | array[i] = array[i + 1] 4 | array[i + 1] = temp 5 | } 6 | function bubbleSort(array) { 7 | for (let j = array.length - 1; j > 0; j--) { 8 | for (let i = 0; i < j; i++) { 9 | if (array[i] > array[i + 1]) { 10 | swap(array, i, j) 11 | } 12 | } 13 | } 14 | } 15 | 16 | const array = [17, 2, 5, 78, 41] 17 | bubbleSort(array) 18 | console.log(array) 19 | -------------------------------------------------------------------------------- /src/javascript/buscaLinearComSentinela.js: -------------------------------------------------------------------------------- 1 | // Função que recebe como parâmetros: um vetor e um elemento a ser buscado. 2 | 3 | // O elemento é adicionado no final do vetor, garantido que ele será encontrado pelo laço. 4 | // Ao sair do laço será verificado se o índice encontrado é igual ao último índice da lista. 5 | // Se eles forem diferentes, significa que o elemento foi encontrado no vetor, retornando o índice. 6 | // Caso forem iguais, significa que o elemento não foi encontrado, retornando -1. 7 | 8 | 9 | function sentinelSearch(array, item) { 10 | array.push(item); 11 | index = 0 12 | 13 | while (array[index] !== item) { 14 | index++ 15 | } 16 | 17 | if (index !== array.length - 1) { 18 | return index 19 | } 20 | 21 | return -1; 22 | } 23 | -------------------------------------------------------------------------------- /src/javascript/fibonacci.js: -------------------------------------------------------------------------------- 1 | function fibonnaci(num) { 2 | var fibonnaciArray = []; 3 | 4 | var t1 = 0; 5 | var t2 = 1; 6 | 7 | if (num < 3) { 8 | if (num === 1) { 9 | fibonnaciArray.push(t1); 10 | } 11 | 12 | else if (num === 2) { 13 | fibonnaciArray.push(t1); 14 | fibonnaciArray.push(t2); 15 | } 16 | } 17 | 18 | else if (num >= 3) { 19 | fibonnaciArray.push(t1); 20 | fibonnaciArray.push(t2); 21 | 22 | var t3 = 0; 23 | 24 | for (var i = 3; i < num+1; i++) { 25 | t3 = t1 + t2; 26 | 27 | fibonnaciArray.push(t3); 28 | 29 | t1 = t2; 30 | t2 = t3; 31 | } 32 | } 33 | 34 | return fibonnaciArray; 35 | } 36 | -------------------------------------------------------------------------------- /src/javascript/insertionSort.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | function insertionSort(array) { 4 | let size = array.length; 5 | for (let i = 1; i < size; i++) { 6 | let atual = array[i]; 7 | let j = i-1; 8 | while ((j > -1) && (atual < array[j])) { 9 | array[j+1] = array[j]; 10 | j--; 11 | } 12 | array[j+1] = atual; 13 | } 14 | return array; 15 | } 16 | 17 | -------------------------------------------------------------------------------- /src/javascript/linearSearch.js: -------------------------------------------------------------------------------- 1 | // Função que recebe como parâmetros: um vetor e um elemento a ser buscado. 2 | // Caso o elemento seja encontrado, é retornado seu índice no array, caso contrário a função retorna -1. 3 | 4 | function linearSearch(array, item) { 5 | lenArray = array.length; 6 | 7 | for (let x = 0; x < lenArray; x++) { 8 | if (array[x] == item) { 9 | return x; 10 | } 11 | } 12 | 13 | return -1; 14 | } 15 | -------------------------------------------------------------------------------- /src/javascript/mergeSort.js: -------------------------------------------------------------------------------- 1 | function mergeSort(array) { 2 | if (array.length <= 1) return array; 3 | 4 | const array1 = mergeSort(array.slice(0, array.length / 2)); 5 | const array2 = mergeSort(array.slice(array.length / 2, array.length)); 6 | 7 | return merge(array1, array2); 8 | } 9 | 10 | function merge(array1, array2) { 11 | const result = []; 12 | 13 | let i = 0; 14 | let j = 0; 15 | 16 | while (i < array1.length && j < array2.length) { 17 | if (array1[i] < array2[j]) { 18 | result.push(array1[i++]); 19 | } else { 20 | result.push(array2[j++]); 21 | } 22 | } 23 | 24 | while (i < array1.length) result.push(array1[i++]); 25 | 26 | while (j < array2.length) result.push(array2[j++]); 27 | 28 | return result; 29 | } 30 | -------------------------------------------------------------------------------- /src/javascript/selectionSort.js: -------------------------------------------------------------------------------- 1 | 2 | function selectionSort(array) { 3 | let size = array.length; 4 | for (let i = 0; i < size; i++) { 5 | let min = i; 6 | for (let j = i + 1; j < size; j++) { 7 | if (array[min] > array[j]) { 8 | min = j; 9 | } 10 | } 11 | if (min !== i) { 12 | let tmp = array[i]; 13 | array[i] = array[min]; 14 | array[min] = tmp; 15 | } 16 | } 17 | return array; 18 | } 19 | 20 | let array = [10,8,3,4,15,42] 21 | selectionSort(array) 22 | console.log(array) -------------------------------------------------------------------------------- /src/python/MergeSort/MergeSort-1.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | # DIVIDE A LISTA EM DUAS PARA O MERGE SORT 4 | def separador(lista): 5 | l1 = [] 6 | l2 = [] 7 | for i in range(0,len(lista)/2): 8 | l1.append(lista[i]) 9 | for i in range(len(lista)/2,len(lista)): 10 | l2.append(lista[i]) 11 | return l1,l2 12 | 13 | # MERGE JUNTA LISTA 14 | def juntalista(lista1,lista2): 15 | novalista = [] 16 | while len(lista1) != 0 and len(lista2) != 0: 17 | if lista1[0] >= lista2[0]: 18 | novalista.append(lista2.pop(0)) 19 | else: 20 | novalista.append(lista1.pop(0)) 21 | if len(lista1) != 0: 22 | for e in lista1: 23 | novalista.append(e) 24 | elif len(lista2) != 0: 25 | for e in lista2: 26 | novalista.append(e) 27 | return novalista 28 | 29 | # SORT 30 | def merge(lista): 31 | # CASOS DE PARADA 32 | if len(lista) < 2: return lista 33 | # RECURSIVIDADE 34 | else: 35 | lis1,lis2 = separador(lista) 36 | return juntalista(merge(lis1),merge(lis2)) 37 | 38 | #Teste 39 | while True: 40 | h = random.sample(range(0,100),100) 41 | if sorted(h) != merge(h): 42 | print h 43 | break 44 | 45 | -------------------------------------------------------------------------------- /src/python/MergeSort/MergeSort-2.py: -------------------------------------------------------------------------------- 1 | def mergeSort(alist): 2 | print("Splitting ",alist) 3 | if len(alist)>1: 4 | mid = len(alist)//2 5 | lefthalf = alist[:mid] 6 | righthalf = alist[mid:] 7 | 8 | mergeSort(lefthalf) 9 | mergeSort(righthalf) 10 | 11 | i=0 12 | j=0 13 | k=0 14 | while i < len(lefthalf) and j < len(righthalf): 15 | if lefthalf[i] < righthalf[j]: 16 | alist[k]=lefthalf[i] 17 | i=i+1 18 | else: 19 | alist[k]=righthalf[j] 20 | j=j+1 21 | k=k+1 22 | 23 | while i < len(lefthalf): 24 | alist[k]=lefthalf[i] 25 | i=i+1 26 | k=k+1 27 | 28 | while j < len(righthalf): 29 | alist[k]=righthalf[j] 30 | j=j+1 31 | k=k+1 32 | print("Merging ",alist) 33 | 34 | alist = [54,26,93,17,77,31,44,55,20] 35 | mergeSort(alist) 36 | print(alist) 37 | -------------------------------------------------------------------------------- /src/python/QuickSort/median_of_three_quick_sort.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def quickSort(array, leftIndex, rightIndex): 4 | if (leftIndex >= rightIndex): return 5 | #Coloca a mediana no inicio do array. 6 | med = mediana(array, leftIndex, rightIndex-1) 7 | array[leftIndex], array[med] = array[med], array[leftIndex] 8 | 9 | #Define o pivot como primeiro elemento. 10 | pivot = array[leftIndex] 11 | 12 | #i, é o valor que define o próximo valor do array a ser trocado -1. 13 | i = leftIndex 14 | 15 | #loop que varre o array procurando os valores menores que o pivot e trocando com o i. 16 | for j in range(i+1, rightIndex): 17 | if (array[j] < pivot): 18 | i += 1 19 | array[i], array[j] = array[j], array[i] 20 | #por fim, troca o i com o pivot, a fim de deixar todos os menores que o pivot na esquerda, e os maiores a direita. 21 | array[i], array[leftIndex] = array[leftIndex], array[i] 22 | 23 | #Executa a mesma ação de forma recursiva até que só sobre um elemento no array. 24 | quickSort(array, leftIndex, i) 25 | quickSort(array, i+1, rightIndex) 26 | 27 | def mediana(array, ini, fim): 28 | a = array[ini] 29 | b = array[int((ini+fim)/2)] 30 | c = array[fim] 31 | if (a < b): 32 | if (b < c): 33 | return int((ini+fim)/2) 34 | else: 35 | if (a < c) : 36 | return fim 37 | else: 38 | return ini 39 | else: 40 | if (c < b): 41 | return int((ini+fim)/2) 42 | else: 43 | if (c < a): 44 | return fim 45 | else: 46 | return ini 47 | 48 | tentativas = 0 49 | #Test 50 | while True: 51 | h = random.sample(range(0,100),100) 52 | ordenada_certa = sorted(h) 53 | quickSort(h, 0, len(h)) 54 | if ordenada_certa != h: 55 | print (h) 56 | break 57 | else: 58 | tentativas += 1 59 | print ("Arrays ordenados com sucesso: "+str(tentativas)) -------------------------------------------------------------------------------- /src/python/QuickSort/simple_quick_sort.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def quickSort(array, leftIndex, rightIndex): 4 | #Define o pivot como primeiro elemento. 5 | pivot = array[leftIndex] 6 | 7 | #i, é o valor que define o próximo valor do array a ser trocado -1. 8 | i = leftIndex 9 | 10 | #loop que varre o array procurando os valores menores que o pivot e trocando com o i. 11 | for j in range(i+1, rightIndex): 12 | if (array[j] < pivot): 13 | i += 1 14 | array[i], array[j] = array[j], array[i] 15 | #por fim, troca o i com o pivot, a fim de deixar todos os menores que o pivot na esquerda, e os maiores a direita. 16 | array[i], array[leftIndex] = array[leftIndex], array[i] 17 | 18 | #Executa a mesma ação de forma recursiva até que só sobre um elemento no array. 19 | quickSort(array, leftIndex, i) 20 | quickSort(array, i+1, rightIndex) 21 | 22 | tentativas = 0 23 | #Test 24 | while True: 25 | h = random.sample(range(0,100),100) 26 | ordenada_certa = sorted(h) 27 | quickSort(h, 0, len(h)) 28 | if ordenada_certa != h: 29 | print (h) 30 | break 31 | else: 32 | tentativas += 1 33 | print ("Arrays ordenados com sucesso: "+str(tentativas)) -------------------------------------------------------------------------------- /src/python/binary_search.py: -------------------------------------------------------------------------------- 1 | def binarySearch(vector, target, left, right): 2 | if (left <= right and len(vector) != 0): 3 | mid = (left + right) / 2 4 | atual = vector[mid] 5 | if (atual == target): 6 | return atual 7 | 8 | elif (atual < target): 9 | return binarySearch(vector, target, mid + 1, right) 10 | elif (atual > target): 11 | return binarySearch(vector, target, left, mid - 1) 12 | return -1 -------------------------------------------------------------------------------- /src/python/bogo.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def bogoSort(a): 4 | while (not is_sorted(a)): 5 | shuffle(a) 6 | 7 | def is_sorted(a): 8 | for i in range(0, len(a)-1): 9 | if (a[i] > a[i+1] ): 10 | return False 11 | return True 12 | 13 | def shuffle(a): 14 | n = len(a) 15 | for i in range (0,n): 16 | r = random.randint(0,n-1) 17 | a[i], a[r] = a[r], a[i] 18 | -------------------------------------------------------------------------------- /src/python/bubble_sort.py: -------------------------------------------------------------------------------- 1 | def bubbleSort(arr): 2 | n = len(arr) 3 | 4 | # Traverse through all array elements 5 | for i in range(n-1): 6 | # range(n) also work but outer loop will repeat one time more than needed. 7 | 8 | # Last i elements are already in place 9 | for j in range(0, n-i-1): 10 | 11 | # traverse the array from 0 to n-i-1 12 | # Swap if the element found is greater 13 | # than the next element 14 | if arr[j] > arr[j+1] : 15 | arr[j], arr[j+1] = arr[j+1], arr[j] 16 | 17 | # Driver code to test above 18 | arr = [64, 34, 25, 12, 22, 11, 90] 19 | 20 | bubbleSort(arr) 21 | 22 | print ("Sorted array is:") 23 | for i in range(len(arr)): 24 | print ("%d" %arr[i]) 25 | -------------------------------------------------------------------------------- /src/python/busca_linear.py: -------------------------------------------------------------------------------- 1 | def busca_linear(array, elemento): 2 | for i in range(len(array)): 3 | if (array[i] == elemento): 4 | return i 5 | return -1 6 | 7 | -------------------------------------------------------------------------------- /src/python/busca_recursiva.py: -------------------------------------------------------------------------------- 1 | def busca_linear_recursiva(array,elemento): 2 | i = -1 3 | return busca_recursiva(array,elemento, i) 4 | 5 | def busca_recursiva(array,elemento, i): 6 | i += 1 7 | if(i == len(array)): 8 | return -1 9 | if(array[i] == elemento): 10 | return i 11 | return busca_recursiva(array,elemento,i) 12 | -------------------------------------------------------------------------------- /src/python/busca_todos_matriz.py: -------------------------------------------------------------------------------- 1 | #passando matriz e valor do elemento como parâmetro 2 | #a funcao retorna uma lista com os pares ordenados de onde o valor e encontrado 3 | 4 | def busca_matriz(m, e): 5 | coordenadas = [] 6 | for i in range(len(m)): 7 | for j in range(len(m[0])): 8 | elemento = matriz[i][j] 9 | if elemento == e: 10 | coordenada = (i, j) 11 | coordenadas.append(coordenada) 12 | 13 | 14 | return coordenadas 15 | 16 | -------------------------------------------------------------------------------- /src/python/fibonacci.py: -------------------------------------------------------------------------------- 1 | def fibonacci(inp) : 2 | 3 | answer = "" 4 | number1 = 0 5 | number2 = 1 6 | switchLoop = True 7 | 8 | for loop in range(inp+1, range > 0, -1): 9 | 10 | if switchLoop : 11 | answer += str(number1) + " " 12 | number1 += number2 13 | switchLoop = False 14 | 15 | elif not switchLoop : 16 | answer += str(number2) + " " 17 | number2 += number1 18 | switchLoop = True 19 | 20 | return answer.strip() -------------------------------------------------------------------------------- /src/python/in.py: -------------------------------------------------------------------------------- 1 | #vai definir se um elemento esta ou nao em uma string 2 | 3 | def funcao_in(string, elemento): 4 | for i in range(len(string)-len(elemento)+1): 5 | if elemento == get_str(string,i,i+len(elemento)): 6 | return True 7 | return False 8 | 9 | def get_str(string,i,f): 10 | nome = "" 11 | for c in range(i,f): 12 | nome += string[c] 13 | return nome 14 | -------------------------------------------------------------------------------- /src/python/insertion_sort.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | #Insertion sort obs: funcao com efeito colateral. 4 | def ordenador_insertion(v): 5 | for i in range(1,len(v)): 6 | j = i 7 | while j > 0 and v[j] < v[j-1]: 8 | temp = v[j] 9 | v[j] = v[j-1] 10 | v[j-1] = temp 11 | j -= 1 12 | 13 | #Test 14 | while True: 15 | h = random.sample(range(0,100),100) 16 | ordenada_certa = sorted(h) 17 | ordenador_insertion(h) 18 | if ordenada_certa != h: 19 | print h 20 | break 21 | 22 | -------------------------------------------------------------------------------- /src/python/matriz_transposta.py: -------------------------------------------------------------------------------- 1 | def transposta(matriz): 2 | 3 | transposta = [] 4 | for j in range(len(matriz[0])): 5 | linha = [] 6 | for i in range(len(matriz)): 7 | linha.append(matriz[i][j]) 8 | 9 | transposta.append(linha) 10 | 11 | return transposta 12 | 13 | -------------------------------------------------------------------------------- /src/python/selection_sort.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implementação do Selection Sort em Python3 3 | ''' 4 | 5 | def menor(lista, inicio): 6 | m = inicio #Assumimos o primeiro elemento da lista como sendo o menor 7 | for i in range(inicio, len(lista)): #Iterando... 8 | if lista[m] > lista[i]: #Se o elemento atual for menor que o que assumimos como menor... 9 | m = i #Este é o novo menor elemento 10 | return m #Retorna o indice do menor elemento 11 | 12 | 13 | def selection_sort(lista): 14 | for i in range(len(lista)): #Iterando a lista e levando os menores para o começo 15 | m = menor(lista, i) #Encontra o menor elemento da lista partindo do ponto não ordenado 16 | if lista[m] < lista[i]: #Se o menor elemento for menor que o primeiro não ordenado... 17 | lista[m], lista[i] = lista[i], lista[m] #Trocamos de lugar 18 | -------------------------------------------------------------------------------- /src/python/slice.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implementação de função de slice em Python3. 3 | A função recebe uma lista, a posição inicial 4 | e a final do corte e retorna uma nova lista 5 | com os elementos do intervalo passado. 6 | 7 | Caso não sejam passados, os parâmetros pos_i é tido 8 | como 0 por default e o pos_f é tido como o tamanho da 9 | lista de origem. 10 | ''' 11 | def slice(array, pos_i=0, pos_f=None): 12 | 13 | if pos_f is None or pos_f >= len(array): #Para casos nos quais a posição final não é passada ou é maior que o tamanho da lista 14 | pos_f = len(array) 15 | elif pos_f < 0: #Para casos nos quais a posição final é negativa 16 | pos_f = len(array) + pos_f 17 | 18 | if pos_i < 0: #Para casos nos quais a posição inicial é negativa 19 | pos_i = len(array) + pos_i 20 | 21 | #Nova lista a ser retornada 22 | new_array = list() 23 | 24 | #Iterando no intervalo [pos_i, pos_f[ da lista 25 | for i in range(pos_i, pos_f): 26 | new_array.append(array[i]) 27 | 28 | return new_array 29 | -------------------------------------------------------------------------------- /src/python/split.py: -------------------------------------------------------------------------------- 1 | def meu_split(texto,separador): 2 | aux = '' 3 | resultado = [] 4 | for termo in range(len(texto)): 5 | if termo != separador: 6 | aux += termo 7 | continue 8 | resultado.append(aux) 9 | aux = '' 10 | return resultado 11 | 12 | --------------------------------------------------------------------------------