- Find Distinct Subsets |
+ Two-Sum Problem |
-
-
+
+
|
-
+
|
-
-
+
+
|
-
-
+
+
|
@@ -3999,8 +4637,8 @@ In order to achieve greater coverage and encourage more people to contribute to
|
-
-
+
+
|
diff --git a/src/c/BinarySearch.c b/src/c/BinarySearch.c
index ae9e5cf5..4ab19f5d 100644
--- a/src/c/BinarySearch.c
+++ b/src/c/BinarySearch.c
@@ -1,43 +1,43 @@
-#include
+#include
int BinarySearch(int array[], int size, int value) {
- int start = 0;
- int end = size - 1;
- int middle = end / 2;
+ int start = 0;
+ int end = size - 1;
+ int middle = end / 2;
- while (start < end && array[middle] != value) {
- // new start
- if (value > array[middle])
- start = middle + 1;
+ while (start < end && array[middle] != value) {
+ // new start
+ if (value > array[middle])
+ start = middle + 1;
- // new end
- if (value < array[middle])
- end = middle - 1;
+ // new end
+ if (value < array[middle])
+ end = middle - 1;
- // new middle
- middle = (start + end) / 2;
- }
+ // new middle
+ middle = (start + end) / 2;
+ }
- if (array[middle] == value)
- return middle;
+ if (array[middle] == value)
+ return middle;
- return -1;
+ return -1;
}
int main() {
- int value;
- int array[] = {1, 5, 10, 12, 18, 22, 87, 90, 112, 129};
- size_t size = sizeof(array) / sizeof(array[0]);
+ int value;
+ int array[] = {1, 5, 10, 12, 18, 22, 87, 90, 112, 129};
+ size_t size = sizeof(array) / sizeof(array[0]);
- printf("Please provide the number you want to value for: ");
- scanf("%d", &value);
+ printf("Please provide the number you want to value for: ");
+ scanf("%d", &value);
- int pos = BinarySearch(array, size, value);
+ int pos = BinarySearch(array, size, value);
- if (pos != -1)
- printf("Found in position = %d.\nValue = %d\n", pos, array[pos]);
- else
- printf("Not found\n");
+ if (pos != -1)
+ printf("Found in position = %d.\nValue = %d\n", pos, array[pos]);
+ else
+ printf("Not found\n");
- return 0;
+ return 0;
}
diff --git a/src/c/BinarySearchTree.c b/src/c/BinarySearchTree.c
index e29bb525..bce19184 100644
--- a/src/c/BinarySearchTree.c
+++ b/src/c/BinarySearchTree.c
@@ -1,207 +1,214 @@
/*
-* Árvore Binária de Busca em C
-*
-* ( 6 )
-* / \
-* ( 2 ) ( 7 )
-* / \ \
-*( 1 ) ( 4 ) ( 8 )
-* / \
-* ( 3 ) ( 5 )
-*/
+ * Árvore Binária de Busca em C
+ *
+ * ( 6 )
+ * / \
+ * ( 2 ) ( 7 )
+ * / \ \
+ *( 1 ) ( 4 ) ( 8 )
+ * / \
+ * ( 3 ) ( 5 )
+ */
-#include
#include
+#include
typedef int TIPOCHAVE;
-typedef struct AUX{
- TIPOCHAVE chave;
- struct AUX *esq, *dir;
-}NO, *PONT; // NO é a estrutura e PONT é um ponteiro de NO
+typedef struct AUX {
+ TIPOCHAVE chave;
+ struct AUX *esq, *dir;
+} NO, *PONT; // NO é a estrutura e PONT é um ponteiro de NO
-int max(int a, int b){
- if( a > b )
- return a;
- return b;
+int max(int a, int b) {
+ if (a > b)
+ return a;
+ return b;
}
-int altura(PONT no){
- if( no == NULL ) // Mesma coisa que usar if(!no)
- return 0;
- return 1 + max( altura(no->esq), altura(no->dir) ); // Percorre a arvore pela esquerda e pela direita para ver qual tem altura maior
+int altura(PONT no) {
+ if (no == NULL) // Mesma coisa que usar if(!no)
+ return 0;
+ return 1 + max(altura(no->esq),
+ altura(no->dir)); // Percorre a arvore pela esquerda e pela
+ // direita para ver qual tem altura maior
}
-PONT buscaBinaria(TIPOCHAVE ch, PONT raiz){
- if( !raiz )
- return NULL;
- if( raiz->chave == ch )
- return raiz;
- if( raiz->chave < ch )
- buscaBinaria(ch, raiz->dir);
- else
- buscaBinaria(ch, raiz->esq);
+PONT buscaBinaria(TIPOCHAVE ch, PONT raiz) {
+ if (!raiz)
+ return NULL;
+ if (raiz->chave == ch)
+ return raiz;
+ if (raiz->chave < ch)
+ buscaBinaria(ch, raiz->dir);
+ else
+ buscaBinaria(ch, raiz->esq);
}
-PONT buscaBinariaLinear(TIPOCHAVE ch, PONT atual){
- while( atual != NULL ){
- if( atual->chave == ch )
- return atual;
- if( atual->chave < ch )
- atual = atual->dir;
- else
- atual = atual->esq;
- }
- return NULL;
+PONT buscaBinariaLinear(TIPOCHAVE ch, PONT atual) {
+ while (atual != NULL) {
+ if (atual->chave == ch)
+ return atual;
+ if (atual->chave < ch)
+ atual = atual->dir;
+ else
+ atual = atual->esq;
+ }
+ return NULL;
}
-PONT criaNo(TIPOCHAVE ch){
- PONT no = (PONT) malloc( sizeof(NO) );
- no->esq = NULL;
- no->dir = NULL;
- no->chave = ch;
- return no;
+PONT criaNo(TIPOCHAVE ch) {
+ PONT no = (PONT)malloc(sizeof(NO));
+ no->esq = NULL;
+ no->dir = NULL;
+ no->chave = ch;
+ return no;
}
-bool inserir(TIPOCHAVE ch, PONT atual){
- PONT ant;
- // Percorre a arvore para a direita ou esquerda até encontrar uma posição NULL (vazia)
- while(atual != NULL){
- ant = atual;
- if( atual->chave < ch )
- atual = atual->dir;
- else
- atual = atual->esq;
- }
- atual = criaNo(ch); // Utiliza a váriavel atual, pois estava 'sobrando'
- if( ant->chave < ch )
- ant->dir = atual;
- else
- ant->esq = atual;
- return true;
+bool inserir(TIPOCHAVE ch, PONT atual) {
+ PONT ant;
+ // Percorre a arvore para a direita ou esquerda até encontrar uma posição NULL
+ // (vazia)
+ while (atual != NULL) {
+ ant = atual;
+ if (atual->chave < ch)
+ atual = atual->dir;
+ else
+ atual = atual->esq;
+ }
+ atual = criaNo(ch); // Utiliza a váriavel atual, pois estava 'sobrando'
+ if (ant->chave < ch)
+ ant->dir = atual;
+ else
+ ant->esq = atual;
+ return true;
}
-PONT buscaNoPai(TIPOCHAVE ch, PONT atual){
- PONT noPai = atual;
- while( atual != NULL ){
- if( atual->chave == ch )
- return noPai;
- noPai = atual;
- if( atual->chave < ch )
- atual = atual->dir;
- else
- atual = atual->esq;
- }
- return noPai;
+PONT buscaNoPai(TIPOCHAVE ch, PONT atual) {
+ PONT noPai = atual;
+ while (atual != NULL) {
+ if (atual->chave == ch)
+ return noPai;
+ noPai = atual;
+ if (atual->chave < ch)
+ atual = atual->dir;
+ else
+ atual = atual->esq;
+ }
+ return noPai;
}
-PONT maiorAesquerda(PONT atual){
- atual = atual->esq;
- while( atual->dir != NULL )
- atual = atual->dir;
- return atual;
+PONT maiorAesquerda(PONT atual) {
+ atual = atual->esq;
+ while (atual->dir != NULL)
+ atual = atual->dir;
+ return atual;
}
-bool excluir(TIPOCHAVE ch, PONT raiz){
- PONT atual, noPai, substituto, paiSubstituto;
- substituto = NULL;
- atual = buscaBinaria(ch, raiz);
- if( atual == NULL ) return false; // Não encontrou a chave
- noPai = buscaNoPai(ch, raiz);
- if( atual->esq == NULL || atual->dir == NULL ){ // Se tem 0 ou 1 filho
- if( atual->esq == NULL )
- substituto = atual->dir;
- else
- substituto = atual->esq;
- if( noPai == NULL ){ // Único que não tem pai é a raiz
- raiz = substituto;
- }else{
- if( ch < noPai->chave)
- noPai->esq = substituto;
- else
- noPai->dir = substituto;
- }
- free(atual);
- }else{
- substituto = maiorAesquerda(atual);
- atual->chave = substituto->chave;
- if( substituto->esq != NULL )
- atual->esq = substituto->esq;
- else
- atual->esq = NULL;
- free(substituto);
- }
- return true;
+bool excluir(TIPOCHAVE ch, PONT raiz) {
+ PONT atual, noPai, substituto, paiSubstituto;
+ substituto = NULL;
+ atual = buscaBinaria(ch, raiz);
+ if (atual == NULL)
+ return false; // Não encontrou a chave
+ noPai = buscaNoPai(ch, raiz);
+ if (atual->esq == NULL || atual->dir == NULL) { // Se tem 0 ou 1 filho
+ if (atual->esq == NULL)
+ substituto = atual->dir;
+ else
+ substituto = atual->esq;
+ if (noPai == NULL) { // Único que não tem pai é a raiz
+ raiz = substituto;
+ } else {
+ if (ch < noPai->chave)
+ noPai->esq = substituto;
+ else
+ noPai->dir = substituto;
+ }
+ free(atual);
+ } else {
+ substituto = maiorAesquerda(atual);
+ atual->chave = substituto->chave;
+ if (substituto->esq != NULL)
+ atual->esq = substituto->esq;
+ else
+ atual->esq = NULL;
+ free(substituto);
+ }
+ return true;
}
-void preordem(PONT no){ // R - E - D
- if( !no ) return;
- printf("%d, ", no->chave);
- preordem(no->esq);
- preordem(no->dir);
+void preordem(PONT no) { // R - E - D
+ if (!no)
+ return;
+ printf("%d, ", no->chave);
+ preordem(no->esq);
+ preordem(no->dir);
}
-void posordem(PONT no){ // E - D - R
- if( !no ) return;
- posordem(no->esq);
- posordem(no->dir);
- printf("%d, ", no->chave);
+void posordem(PONT no) { // E - D - R
+ if (!no)
+ return;
+ posordem(no->esq);
+ posordem(no->dir);
+ printf("%d, ", no->chave);
}
-void emordem(PONT no){ // E - R - D
- if( !no ) return;
- emordem(no->esq);
- printf("%d, ", no->chave);
- emordem(no->dir);
+void emordem(PONT no) { // E - R - D
+ if (!no)
+ return;
+ emordem(no->esq);
+ printf("%d, ", no->chave);
+ emordem(no->dir);
}
// Esta função não está funcionando
-bool insereRecursivo(TIPOCHAVE ch, PONT no){
- PONT ant;
- if( !no ){
- no = criaNo(ch);
- }else{
- ant = no;
- if( ch < no->chave )
- insereRecursivo(ch, no->esq);
- else
- insereRecursivo(ch, no->dir);
- }
- if( ant->chave < ch )
- ant->dir = no;
- else
- ant->esq = no;
- return true;
+bool insereRecursivo(TIPOCHAVE ch, PONT no) {
+ PONT ant;
+ if (!no) {
+ no = criaNo(ch);
+ } else {
+ ant = no;
+ if (ch < no->chave)
+ insereRecursivo(ch, no->esq);
+ else
+ insereRecursivo(ch, no->dir);
+ }
+ if (ant->chave < ch)
+ ant->dir = no;
+ else
+ ant->esq = no;
+ return true;
}
-int main(){
- PONT noArvore = criaNo(6);
-
- inserir(2, noArvore);
- inserir(1, noArvore);
- inserir(4, noArvore);
- inserir(7, noArvore);
- inserir(8, noArvore);
- inserir(3, noArvore);
- inserir(5, noArvore);
-
- int valorBuscado = 7;
- if( buscaBinaria(valorBuscado, noArvore) )
- printf("Busca : %d\n", buscaBinaria(valorBuscado, noArvore)->chave );
- else
- printf("Não encontrou\n");
-
- excluir(4, noArvore);
-
- printf("Pre-ordem: ");
- preordem(noArvore);
- printf("\n");
- printf("Em-ordem: ");
- emordem(noArvore);
- printf("\n");
- printf("Pos-ordem: ");
- posordem(noArvore);
-
- printf("\nAltura: %d\n", altura(noArvore) );
- return 0;
+int main() {
+ PONT noArvore = criaNo(6);
+
+ inserir(2, noArvore);
+ inserir(1, noArvore);
+ inserir(4, noArvore);
+ inserir(7, noArvore);
+ inserir(8, noArvore);
+ inserir(3, noArvore);
+ inserir(5, noArvore);
+
+ int valorBuscado = 7;
+ if (buscaBinaria(valorBuscado, noArvore))
+ printf("Busca : %d\n", buscaBinaria(valorBuscado, noArvore)->chave);
+ else
+ printf("Não encontrou\n");
+
+ excluir(4, noArvore);
+
+ printf("Pre-ordem: ");
+ preordem(noArvore);
+ printf("\n");
+ printf("Em-ordem: ");
+ emordem(noArvore);
+ printf("\n");
+ printf("Pos-ordem: ");
+ posordem(noArvore);
+
+ printf("\nAltura: %d\n", altura(noArvore));
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/BinaryTree.c b/src/c/BinaryTree.c
index 1d7e5a51..b1b6a162 100644
--- a/src/c/BinaryTree.c
+++ b/src/c/BinaryTree.c
@@ -5,198 +5,188 @@
struct No {
- int valor;
- struct No* esquerda;
- struct No* direita;
- int altura;
+ int valor;
+ struct No *esquerda;
+ struct No *direita;
+ int altura;
};
-int altura(struct No *n){
+int altura(struct No *n) {
- if(n == NULL)
- return 0;
- return n->altura;
+ if (n == NULL)
+ return 0;
+ return n->altura;
}
-int max(int a, int b){
- return (a > b)? a : b;
-}
+int max(int a, int b) { return (a > b) ? a : b; }
-struct No* novoNo(int valor){
+struct No *novoNo(int valor) {
- struct No* novoNo = (struct No*)malloc(sizeof(struct No));
+ struct No *novoNo = (struct No *)malloc(sizeof(struct No));
- novoNo->valor = valor;
- novoNo->esquerda = NULL;
- novoNo->direita = NULL;
- novoNo->altura = 1;
-
- return novoNo;
+ novoNo->valor = valor;
+ novoNo->esquerda = NULL;
+ novoNo->direita = NULL;
+ novoNo->altura = 1;
+
+ return novoNo;
}
-struct No* inserir(struct No* raiz, int valor){
+struct No *inserir(struct No *raiz, int valor) {
- if(raiz == NULL){
- return novoNo(valor);
- }
- if(valor <= raiz->valor) {
- raiz->esquerda = inserir(raiz->esquerda, valor);
- }
- else {
- raiz->direita = inserir(raiz->direita, valor);
- }
+ if (raiz == NULL) {
+ return novoNo(valor);
+ }
+ if (valor <= raiz->valor) {
+ raiz->esquerda = inserir(raiz->esquerda, valor);
+ } else {
+ raiz->direita = inserir(raiz->direita, valor);
+ }
- raiz->altura = 1 + max(altura(raiz->esquerda), altura(raiz->direita));
+ raiz->altura = 1 + max(altura(raiz->esquerda), altura(raiz->direita));
- return raiz;
+ return raiz;
}
-int busca(struct No* raiz, int valor){
-
- if(raiz == NULL){
- printf(" Valor [%d] não encontrado.\n", valor);
- }
- else if(raiz->valor == valor){
- printf(" Valor [%d] encontrado.\n", valor);
- }
- else if(valor <= raiz->valor){
- return busca(raiz->esquerda, valor);
- }
- else if(valor >= raiz->valor){
- return busca(raiz->direita, valor);
- }
+int busca(struct No *raiz, int valor) {
+
+ if (raiz == NULL) {
+ printf(" Valor [%d] não encontrado.\n", valor);
+ } else if (raiz->valor == valor) {
+ printf(" Valor [%d] encontrado.\n", valor);
+ } else if (valor <= raiz->valor) {
+ return busca(raiz->esquerda, valor);
+ } else if (valor >= raiz->valor) {
+ return busca(raiz->direita, valor);
+ }
}
-void preorder(struct No* raiz){
+void preorder(struct No *raiz) {
- if(raiz == NULL) return;
- printf("[%d]", raiz->valor);
- preorder(raiz->esquerda);
- preorder(raiz->direita);
+ if (raiz == NULL)
+ return;
+ printf("[%d]", raiz->valor);
+ preorder(raiz->esquerda);
+ preorder(raiz->direita);
}
-void inorder(struct No* raiz){
+void inorder(struct No *raiz) {
- if(raiz == NULL) return;
- inorder(raiz->esquerda);
- printf("[%d]", raiz->valor);
- inorder(raiz->direita);
+ if (raiz == NULL)
+ return;
+ inorder(raiz->esquerda);
+ printf("[%d]", raiz->valor);
+ inorder(raiz->direita);
}
-void postorder(struct No* raiz){
-
- if(raiz == NULL) return;
- postorder(raiz->esquerda);
- postorder(raiz->direita);
- printf("[%d]", raiz->valor);
+void postorder(struct No *raiz) {
+
+ if (raiz == NULL)
+ return;
+ postorder(raiz->esquerda);
+ postorder(raiz->direita);
+ printf("[%d]", raiz->valor);
}
-void levelOrder(struct No* raiz, int level){
+void levelOrder(struct No *raiz, int level) {
- if(raiz == NULL){
- return;
- }
- if(level == 0){
- printf("[%d]", raiz->valor);
- }
- else{
- levelOrder(raiz->esquerda, level-1);
- levelOrder(raiz->direita, level-1);
- }
+ if (raiz == NULL) {
+ return;
+ }
+ if (level == 0) {
+ printf("[%d]", raiz->valor);
+ } else {
+ levelOrder(raiz->esquerda, level - 1);
+ levelOrder(raiz->direita, level - 1);
+ }
}
-void printLevelOrder(struct No* raiz){
- int h = altura(raiz);
- for(int i = 0; i < h; i++){
- levelOrder(raiz, i);
- }
+void printLevelOrder(struct No *raiz) {
+ int h = altura(raiz);
+ for (int i = 0; i < h; i++) {
+ levelOrder(raiz, i);
+ }
}
-struct No* encontraMenor(struct No* raiz){
- struct No* atual = raiz;
- while(atual->esquerda != NULL){
- atual = atual->esquerda;
- }
- return atual;
+struct No *encontraMenor(struct No *raiz) {
+ struct No *atual = raiz;
+ while (atual->esquerda != NULL) {
+ atual = atual->esquerda;
+ }
+ return atual;
}
+struct No *deleta(struct No *raiz, int valor) {
-struct No* deleta(struct No* raiz, int valor){
-
- if(raiz == NULL){
- return raiz;
- }
- if(valor < raiz->valor) {
- raiz->esquerda = deleta(raiz->esquerda, valor);
- }
- else if(valor > raiz->valor){
- raiz->direita = deleta(raiz->direita, valor);
- }
- else{
- if( (raiz->esquerda == NULL) || (raiz->direita == NULL) ){
- struct No* temp = raiz->esquerda ? raiz->esquerda : raiz->direita;
-
- if(temp == NULL){
- temp = raiz;
- raiz = NULL;
- } else{
- *raiz = *temp;
- free(temp);
- }
- }
- else{
- struct No* temp = encontraMenor(raiz->direita);
- raiz->valor = temp->valor;
- raiz->direita = deleta(raiz->direita, temp->valor);
- }
- }
-
- if(raiz == NULL){
- return raiz;
+ if (raiz == NULL) {
+ return raiz;
+ }
+ if (valor < raiz->valor) {
+ raiz->esquerda = deleta(raiz->esquerda, valor);
+ } else if (valor > raiz->valor) {
+ raiz->direita = deleta(raiz->direita, valor);
+ } else {
+ if ((raiz->esquerda == NULL) || (raiz->direita == NULL)) {
+ struct No *temp = raiz->esquerda ? raiz->esquerda : raiz->direita;
+
+ if (temp == NULL) {
+ temp = raiz;
+ raiz = NULL;
+ } else {
+ *raiz = *temp;
+ free(temp);
+ }
+ } else {
+ struct No *temp = encontraMenor(raiz->direita);
+ raiz->valor = temp->valor;
+ raiz->direita = deleta(raiz->direita, temp->valor);
}
+ }
- raiz->altura = 1 + max(altura(raiz->esquerda), altura(raiz->direita));
-
+ if (raiz == NULL) {
return raiz;
-}
+ }
+ raiz->altura = 1 + max(altura(raiz->esquerda), altura(raiz->direita));
-int main(void){
+ return raiz;
+}
- struct No* raiz;
- raiz = inserir(raiz, 10);
- raiz = inserir(raiz, 2);
- raiz = inserir(raiz, 33);
- raiz = inserir(raiz, 4);
- raiz = inserir(raiz, 57);
- raiz = inserir(raiz, 6);
- raiz = inserir(raiz, 12);
+int main(void) {
- busca(raiz, 33);
- busca(raiz, 23);
+ struct No *raiz;
+ raiz = inserir(raiz, 10);
+ raiz = inserir(raiz, 2);
+ raiz = inserir(raiz, 33);
+ raiz = inserir(raiz, 4);
+ raiz = inserir(raiz, 57);
+ raiz = inserir(raiz, 6);
+ raiz = inserir(raiz, 12);
- printf("\n Preorder: ");
- preorder(raiz);
+ busca(raiz, 33);
+ busca(raiz, 23);
- printf("\n Inorder: ");
- inorder(raiz);
+ printf("\n Preorder: ");
+ preorder(raiz);
- printf("\n Postorder: ");
- postorder(raiz);
+ printf("\n Inorder: ");
+ inorder(raiz);
- printf("\n Levelorder: ");
- printLevelOrder(raiz);
+ printf("\n Postorder: ");
+ postorder(raiz);
- raiz = deleta(raiz, 7);
+ printf("\n Levelorder: ");
+ printLevelOrder(raiz);
- printf("\n Levelorder: ");
- printLevelOrder(raiz);
+ raiz = deleta(raiz, 7);
- raiz = deleta(raiz, 6);
+ printf("\n Levelorder: ");
+ printLevelOrder(raiz);
- printf("\n Levelorder: ");
- printLevelOrder(raiz);
+ raiz = deleta(raiz, 6);
- return 0;
+ printf("\n Levelorder: ");
+ printLevelOrder(raiz);
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/BubbleSort.c b/src/c/BubbleSort.c
index 2b083c47..54e8dc44 100644
--- a/src/c/BubbleSort.c
+++ b/src/c/BubbleSort.c
@@ -1,38 +1,32 @@
#include
-void swap(int array[], int j)
-{
- int t = array[j];
- array[j] = array[j + 1];
- array[j + 1] = t;
+void swap(int array[], int j) {
+ int t = array[j];
+ array[j] = array[j + 1];
+ array[j + 1] = t;
}
-void bubble_sort(int array[], int n)
-{
- for (int i = 0; i < n - 1; i++)
- {
- for (int j = 0; j < n - i - 1; j++)
- {
- if (array[j] > array[j + 1])
- {
- swap(array, j);
- }
- }
+void bubble_sort(int array[], int n) {
+ for (int i = 0; i < n - 1; i++) {
+ for (int j = 0; j < n - i - 1; j++) {
+ if (array[j] > array[j + 1]) {
+ swap(array, j);
+ }
}
+ }
}
-int main()
-{
- int array_size = 9;
- int array[10] = {99, 33, 22, 10, 5, 7, 9, 0, 15, 27};
+int main() {
+ int array_size = 9;
+ int array[10] = {99, 33, 22, 10, 5, 7, 9, 0, 15, 27};
- bubble_sort(array, array_size);
+ bubble_sort(array, array_size);
- printf("Lista ordenada:\n");
- for (int i = 0; i < array_size - 1; i++)
- printf("%d, ", array[i]);
+ printf("Lista ordenada:\n");
+ for (int i = 0; i < array_size - 1; i++)
+ printf("%d, ", array[i]);
- printf("%d\n", array[array_size - 1]);
+ printf("%d\n", array[array_size - 1]);
- return 0;
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/CalculatePi.c b/src/c/CalculatePi.c
index a66e63f9..f104a9ff 100644
--- a/src/c/CalculatePi.c
+++ b/src/c/CalculatePi.c
@@ -4,25 +4,22 @@ Calculo de Pi em C
#include
-float leibniz_pi_calculation(int number)
-{
- float denominador = 1.0f;
- float operacao = 1.0f;
- float pi = 0.0f;
- for (int i = 0; i < number; i++)
- {
- pi += operacao * (4.0 / denominador);
- denominador += 2.0;
- operacao = operacao * -1.0;
- }
- return pi;
+float leibniz_pi_calculation(int number) {
+ float denominador = 1.0f;
+ float operacao = 1.0f;
+ float pi = 0.0f;
+ for (int i = 0; i < number; i++) {
+ pi += operacao * (4.0 / denominador);
+ denominador += 2.0;
+ operacao = operacao * -1.0;
+ }
+ return pi;
}
-int main()
-{
- int n_terms[4] = {10, 1000, 100000, 10000000};
- for (int n = 0; n < 4; n++)
- printf("PI (%i): {%f}\n", n, leibniz_pi_calculation(n_terms[n]));
+int main() {
+ int n_terms[4] = {10, 1000, 100000, 10000000};
+ for (int n = 0; n < 4; n++)
+ printf("PI (%i): {%f}\n", n, leibniz_pi_calculation(n_terms[n]));
- return 0;
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/CircularLinkedList.c b/src/c/CircularLinkedList.c
index c1ebdfcc..0593d07c 100644
--- a/src/c/CircularLinkedList.c
+++ b/src/c/CircularLinkedList.c
@@ -1,104 +1,114 @@
/*
-*
-* Lista Ligada com Nó Cabeça, Circular e Ordenada (Implementação Dinâmica)
-*
-*/
+ *
+ * Lista Ligada com Nó Cabeça, Circular e Ordenada (Implementação Dinâmica)
+ *
+ */
-#include
#include
+#include
typedef int TIPOCHAVE; // Tipo de ID de cada nó da lista
// Estrutura de dados que representa cada nó da lista
-typedef struct AUX{
- TIPOCHAVE chave;
- struct AUX* prox;
-}NO, *PONT;
-
-typedef struct{
- PONT cab; // Nó cabeça
-}LISTA;
-
-void inicializar(LISTA *L){
- // Nó cabeça não deixa a lista ficar vazia, também pode ser usado como sentinela
- L->cab = (PONT) malloc( sizeof(NO) );
- L->cab->prox = L->cab; // Começa apontando para o próprio nó, pois é circular
+typedef struct AUX {
+ TIPOCHAVE chave;
+ struct AUX *prox;
+} NO, *PONT;
+
+typedef struct {
+ PONT cab; // Nó cabeça
+} LISTA;
+
+void inicializar(LISTA *L) {
+ // Nó cabeça não deixa a lista ficar vazia, também pode ser usado como
+ // sentinela
+ L->cab = (PONT)malloc(sizeof(NO));
+ L->cab->prox = L->cab; // Começa apontando para o próprio nó, pois é circular
}
-// Como neste método não irá alterar a lista, pode ser passado uma cópia dela e não necessáriamente um ponteiro para ela
-PONT buscaSequencial(TIPOCHAVE ch, LISTA L, PONT* ant){
- *ant = L.cab; // Sendo uma cópia pode-se usar o ponto (.) no lugar de seta (->), o ant guarda o ponteiro para o nó encontrado
- PONT pos = L.cab->prox;
- L.cab->chave = ch; // Grava o valor no nó cabeça para ser utilizado como sentinela, será o último a ser comparado
- while(pos->chave != ch){
- *ant = pos; // Guarda o ponteiro para o nó
- pos = pos->prox; // Vai para o próximo nó
- }
- if( pos != L.cab ) // Se o nó não é o nó cabeça é pq encontrou
- return pos; // Retorna o nó
- else
- return NULL; // Senão não encontrou retorna NULL
+// Como neste método não irá alterar a lista, pode ser passado uma cópia dela e
+// não necessáriamente um ponteiro para ela
+PONT buscaSequencial(TIPOCHAVE ch, LISTA L, PONT *ant) {
+ *ant = L.cab; // Sendo uma cópia pode-se usar o ponto (.) no lugar de seta
+ // (->), o ant guarda o ponteiro para o nó encontrado
+ PONT pos = L.cab->prox;
+ L.cab->chave = ch; // Grava o valor no nó cabeça para ser utilizado como
+ // sentinela, será o último a ser comparado
+ while (pos->chave != ch) {
+ *ant = pos; // Guarda o ponteiro para o nó
+ pos = pos->prox; // Vai para o próximo nó
+ }
+ if (pos != L.cab) // Se o nó não é o nó cabeça é pq encontrou
+ return pos; // Retorna o nó
+ else
+ return NULL; // Senão não encontrou retorna NULL
}
-bool excluir(TIPOCHAVE ch, LISTA *L){
- PONT aux, ant;
- aux = buscaSequencial(ch, *L, &ant); // Busca o valor para excluir, o ant é passado como endereço de memória, assim a função busca altera ele, guardando o valor anterior
- if( aux == NULL ) return false; // Não encontrou
- ant->prox = aux->prox; // Nó anterior aponta para o próximo, no caso o próximo que o nó a ser excluído está apontando
- free(aux); // Libera a memória
- return true;
+bool excluir(TIPOCHAVE ch, LISTA *L) {
+ PONT aux, ant;
+ aux = buscaSequencial(ch, *L,
+ &ant); // Busca o valor para excluir, o ant é passado
+ // como endereço de memória, assim a função busca
+ // altera ele, guardando o valor anterior
+ if (aux == NULL)
+ return false; // Não encontrou
+ ant->prox = aux->prox; // Nó anterior aponta para o próximo, no caso o próximo
+ // que o nó a ser excluído está apontando
+ free(aux); // Libera a memória
+ return true;
}
-void inserir(TIPOCHAVE ch, LISTA *L){
- PONT ant = L->cab; // O ant guarda o ponteiro para o nó anterior
- PONT pos = L->cab->prox; // O pos guarda o ponteiro para o atual
-
- while(pos->chave < ch && pos != L->cab){
- ant = pos; // Guarda o ponteiro para o nó atual, que será o anterior
- pos = pos->prox; // Vai para o próximo nó
- }
- // Quando encontrou a posição correta na ordem crescente
- PONT novo_no = (PONT) malloc( sizeof(NO) ); // Cria um novo nó
- novo_no->chave = ch; // Coloca a chave no nó
- novo_no->prox = pos; // Aponta para o próximo nó
- ant->prox = novo_no; // Nó anterior aponta para o novo nó
+void inserir(TIPOCHAVE ch, LISTA *L) {
+ PONT ant = L->cab; // O ant guarda o ponteiro para o nó anterior
+ PONT pos = L->cab->prox; // O pos guarda o ponteiro para o atual
+
+ while (pos->chave < ch && pos != L->cab) {
+ ant = pos; // Guarda o ponteiro para o nó atual, que será o anterior
+ pos = pos->prox; // Vai para o próximo nó
+ }
+ // Quando encontrou a posição correta na ordem crescente
+ PONT novo_no = (PONT)malloc(sizeof(NO)); // Cria um novo nó
+ novo_no->chave = ch; // Coloca a chave no nó
+ novo_no->prox = pos; // Aponta para o próximo nó
+ ant->prox = novo_no; // Nó anterior aponta para o novo nó
}
-PONT mostrarLista(LISTA L){
- PONT pos = L.cab->prox; // Pos recebe o primeiro elemento depois do nó cabeça
- while(pos != L.cab){ // Se não for o nó cabeça, a lista não está vazia
- printf("[ %d ]->", pos->chave); // Mostra o valor do nó
- pos = pos->prox; // Vai para o próximo nó
- }printf("\n");
+PONT mostrarLista(LISTA L) {
+ PONT pos = L.cab->prox; // Pos recebe o primeiro elemento depois do nó cabeça
+ while (pos != L.cab) { // Se não for o nó cabeça, a lista não está vazia
+ printf("[ %d ]->", pos->chave); // Mostra o valor do nó
+ pos = pos->prox; // Vai para o próximo nó
+ }
+ printf("\n");
}
-int main(){
-
- LISTA lista;
- inicializar(&lista);
+int main() {
+
+ LISTA lista;
+ inicializar(&lista);
- inserir(4, &lista);
- inserir(6, &lista);
- inserir(2, &lista);
- inserir(3, &lista);
- inserir(1, &lista);
- inserir(5, &lista);
+ inserir(4, &lista);
+ inserir(6, &lista);
+ inserir(2, &lista);
+ inserir(3, &lista);
+ inserir(1, &lista);
+ inserir(5, &lista);
- mostrarLista(lista);
+ mostrarLista(lista);
- excluir(2, &lista);
- excluir(4, &lista);
- excluir(6, &lista);
+ excluir(2, &lista);
+ excluir(4, &lista);
+ excluir(6, &lista);
- mostrarLista(lista);
+ mostrarLista(lista);
- // Exemplo de busca na lista
- PONT aux;
- int valor = 2;
- if( buscaSequencial(valor, lista, &aux) != NULL )
- printf("Valor %d encontrado.\n", valor );
- else
- printf("Valor %d não encontrado.\n", valor);
+ // Exemplo de busca na lista
+ PONT aux;
+ int valor = 2;
+ if (buscaSequencial(valor, lista, &aux) != NULL)
+ printf("Valor %d encontrado.\n", valor);
+ else
+ printf("Valor %d não encontrado.\n", valor);
- return 0;
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/ConnectedComponents.c b/src/c/ConnectedComponents.c
index cc3a5507..122f8575 100644
--- a/src/c/ConnectedComponents.c
+++ b/src/c/ConnectedComponents.c
@@ -1,30 +1,31 @@
/*
-*
-* Grafos - Algoritmo para calcular o número de componentes conexos em um determinado Grafo
-*
-* GRAFO
-* (0) (1)-------------(4)---------------(5)
-* | | | |
-* | | | |
-* | | | |
-* (2) (3)--------------- |
-* | |
-* -----------------------------------
-*
-*
-* Matriz de Adjacência
-* 0 1 2 3 4 5
-* 0 0 - 1 - - -
-* 1 - 0 - 1 1 -
-* 2 1 - 0 - - -
-* 3 - 1 - 0 1 1
-* 4 - 1 - 1 0 1
-* 5 - - - 1 1 0
-*
-*
-* 6 Vértices
-* 8 Arestas
-*/
+ *
+ * Grafos - Algoritmo para calcular o número de componentes conexos em um
+ *determinado Grafo
+ *
+ * GRAFO
+ * (0) (1)-------------(4)---------------(5)
+ * | | | |
+ * | | | |
+ * | | | |
+ * (2) (3)--------------- |
+ * | |
+ * -----------------------------------
+ *
+ *
+ * Matriz de Adjacência
+ * 0 1 2 3 4 5
+ * 0 0 - 1 - - -
+ * 1 - 0 - 1 1 -
+ * 2 1 - 0 - - -
+ * 3 - 1 - 0 1 1
+ * 4 - 1 - 1 0 1
+ * 5 - - - 1 1 0
+ *
+ *
+ * 6 Vértices
+ * 8 Arestas
+ */
#include
@@ -34,35 +35,36 @@
bool visitados[VERTICES];
int componentes = 0;
-int matriz[VERTICES][VERTICES] = { { 0, INF, 1, INF, INF, INF },
- { INF, 0, INF, 1, 1, INF },
- { 1, INF, 0, INF, INF, INF },
- { INF, 1, INF, 0, 1, 1 },
- { INF, 1, INF, 1, 0, 1 },
- { INF, INF, INF, 1, 1, 0 } };
+int matriz[VERTICES][VERTICES] = {
+ {0, INF, 1, INF, INF, INF}, {INF, 0, INF, 1, 1, INF},
+ {1, INF, 0, INF, INF, INF}, {INF, 1, INF, 0, 1, 1},
+ {INF, 1, INF, 1, 0, 1}, {INF, INF, INF, 1, 1, 0}};
-// Método recursivo que encontra os componentes conexos a partir de uma matriz de adjacências
-void calculaComponentesConexos(int atual){
- for (int i = 0; i < VERTICES; i++){
- if( visitados[i] == false && matriz[atual][i] == 1 ){
- visitados[i] = true;
- componentes++;
- printf("(%d)-", i);
- calculaComponentesConexos(i);
- }
- }
+// Método recursivo que encontra os componentes conexos a partir de uma matriz
+// de adjacências
+void calculaComponentesConexos(int atual) {
+ for (int i = 0; i < VERTICES; i++) {
+ if (visitados[i] == false && matriz[atual][i] == 1) {
+ visitados[i] = true;
+ componentes++;
+ printf("(%d)-", i);
+ calculaComponentesConexos(i);
+ }
+ }
}
-int main(){
- for (int i = 0; i < VERTICES; i++)
- visitados[i] = false;
+int main() {
+ for (int i = 0; i < VERTICES; i++)
+ visitados[i] = false;
- for (int i = 0; i < VERTICES; i++)
- if( visitados[i] == false ){
- componentes = 0;
- calculaComponentesConexos(i);
- printf("\nNumero de componentes conexos iniciando pelo vertice %d: %d\n\n", i, componentes);
- }
-
- return 0;
+ for (int i = 0; i < VERTICES; i++)
+ if (visitados[i] == false) {
+ componentes = 0;
+ calculaComponentesConexos(i);
+ printf(
+ "\nNumero de componentes conexos iniciando pelo vertice %d: %d\n\n",
+ i, componentes);
+ }
+
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/CountingSort.c b/src/c/CountingSort.c
index 523fb7a4..bebad0e8 100644
--- a/src/c/CountingSort.c
+++ b/src/c/CountingSort.c
@@ -1,61 +1,66 @@
#include
#include
-// CountingSort - Ordenação por Contagem - Matheus Martins Batista - Universidade Federal de Itajuba - 2021
+// CountingSort - Ordenação por Contagem - Matheus Martins Batista -
+// Universidade Federal de Itajuba - 2021
-// Necessário encontrar o maior elemento para alocar o vetor auxiliar de contagem
-int findMax (int *arr, int tam) {
- int max = arr[0];
+// Necessário encontrar o maior elemento para alocar o vetor auxiliar de
+// contagem
+int findMax(int *arr, int tam) {
+ int max = arr[0];
- for (int i = 1; i < tam; i++) {
- if (arr[i] > max) {
- max = arr[i];
- }
+ for (int i = 1; i < tam; i++) {
+ if (arr[i] > max) {
+ max = arr[i];
}
+ }
- return max;
+ return max;
}
// Ordena os valores presentes em A e armazena em B
void countingSort(int *arrA, int *arrB, int tam) {
- // Vetor de contagem terá a frequência que um número aparece no vetor
- // deve-se setar 0 para todos os elementos ou usar calloc
- int max = findMax(arrA, tam);
- int* count = calloc(max + 1, sizeof(int));
-
- // Frequência que determinado valor aparece no vetor
- for (int i = 0; i < tam; i++) {
- count[arrA[i]]++;
- }
+ // Vetor de contagem terá a frequência que um número aparece no vetor
+ // deve-se setar 0 para todos os elementos ou usar calloc
+ int max = findMax(arrA, tam);
+ int *count = calloc(max + 1, sizeof(int));
- // Acumulativo da frequência dos valores menores que um elemento i do vetor original (A)
- for (int i = 1; i <= max; i++) {
- count[i] += count[i - 1];
- }
+ // Frequência que determinado valor aparece no vetor
+ for (int i = 0; i < tam; i++) {
+ count[arrA[i]]++;
+ }
- // Percorrer o vetor original com início no último elemento, subtituindo os indices nos elementos do vetor count e decrescendo a cada atribuição
- for (int i = tam - 1; i >= 0; i--) {
- arrB[count[arrA[i]] - 1] = arrA[i];
- count[arrA[i]]--;
- }
+ // Acumulativo da frequência dos valores menores que um elemento i do vetor
+ // original (A)
+ for (int i = 1; i <= max; i++) {
+ count[i] += count[i - 1];
+ }
+
+ // Percorrer o vetor original com início no último elemento, subtituindo os
+ // indices nos elementos do vetor count e decrescendo a cada atribuição
+ for (int i = tam - 1; i >= 0; i--) {
+ arrB[count[arrA[i]] - 1] = arrA[i];
+ count[arrA[i]]--;
+ }
}
int main() {
- int *arrA, *arrB;
- int tam = 10;
- arrA = malloc(tam * sizeof(int));
- arrB = calloc(tam, sizeof(int));
+ int *arrA, *arrB;
+ int tam = 10;
+ arrA = malloc(tam * sizeof(int));
+ arrB = calloc(tam, sizeof(int));
- // Popular vetor A
- srand(48+tam);
- for(int j = 0; j < tam; j++) arrA[j] = rand()%100;
+ // Popular vetor A
+ srand(48 + tam);
+ for (int j = 0; j < tam; j++)
+ arrA[j] = rand() % 100;
- countingSort(arrA, arrB, tam);
+ countingSort(arrA, arrB, tam);
- printf("Vetor ordenado: ");
- for (int i = 0; i < tam; i++) {
- printf("%d ", arrB[i]);
- }
+ printf("Vetor ordenado: ");
+ for (int i = 0; i < tam; i++) {
+ printf("%d ", arrB[i]);
+ }
- return 0;
+ return 0;
}
diff --git a/src/c/Dijkstra.c b/src/c/Dijkstra.c
index 806ddbb2..107e0acf 100644
--- a/src/c/Dijkstra.c
+++ b/src/c/Dijkstra.c
@@ -1,98 +1,110 @@
/*
-* Graphs - Dijkstra Algorithm in C
-* Complexity: Theta(n^2)
-*
-* 1 for all - Edges with non-negative weights - Greedy algorithm
-* Finds the shortest path from one vertex (start) to another (destination)
-*
-* Graph with 5 vertices and 6 edges
-*
-* 6
-* (0)-----------------(1)
-* | |
-* 10 | | 2
-* | 1 |
-* (2)-----------------(3)
-* \ /
-* 3 \ / 8
-* \ /
-* -----(4)-----
-*
-* Distance Matrix
-* 0 1 2 3 4
-* 0 0 6 10 - -
-* 1 6 0 - 2 -
-* 2 10 - 0 1 3
-* 3 - 2 1 0 8
-* 4 - - 3 8 0
-*
-* For infinite values, the value will be considered: 4294967295
-* The objective is to leave the starting point (0) and reach the destination (4) by the shortest route
-* Response: (0)->(1)->(3)->(2)->(4) = 12
-*
-*/
+ * Graphs - Dijkstra Algorithm in C
+ * Complexity: Theta(n^2)
+ *
+ * 1 for all - Edges with non-negative weights - Greedy algorithm
+ * Finds the shortest path from one vertex (start) to another (destination)
+ *
+ * Graph with 5 vertices and 6 edges
+ *
+ * 6
+ * (0)-----------------(1)
+ * | |
+ * 10 | | 2
+ * | 1 |
+ * (2)-----------------(3)
+ * \ /
+ * 3 \ / 8
+ * \ /
+ * -----(4)-----
+ *
+ * Distance Matrix
+ * 0 1 2 3 4
+ * 0 0 6 10 - -
+ * 1 6 0 - 2 -
+ * 2 10 - 0 1 3
+ * 3 - 2 1 0 8
+ * 4 - - 3 8 0
+ *
+ * For infinite values, the value will be considered: 4294967295
+ * The objective is to leave the starting point (0) and reach the destination
+ * (4) by the shortest route Response: (0)->(1)->(3)->(2)->(4) = 12
+ *
+ */
-#include
#include
+#include
-#define noVertices 5 // Defines a constant 5 which is the number of vertices in the graph
+#define noVertices \
+ 5 // Defines a constant 5 which is the number of vertices in the graph
-// Dijkstra's algorithm takes as parameters the distance matrix and the number of vertices
-void Dijkstra(unsigned long int matrix[noVertices][noVertices], int n){
-
-bool visited[n]; // Variable that holds true for visited vertices
+// Dijkstra's algorithm takes as parameters the distance matrix and the number
+// of vertices
+void Dijkstra(unsigned long int matrix[noVertices][noVertices], int n) {
- // The value 'i' from the for below is not used, as the for is only used to traverse the entire number of columns in the matrix
- for(int i = 1; i < n; i++){ // Starts at 1 because you don't need to compare the vertex with itself
+ bool visited[n]; // Variable that holds true for visited vertices
-int min = -1; // Variable that stores the position of the smallest value, starts at -1 as it is an invalid position
- unsigned long int MinValue = 4294967295; // Variable that stores the smallest value found, starts with 'infinity', so always on the first pass the value will be smaller than this variable
- // For that loops through all rows in column [0]
- for(int j = 1; j < n; j++){
- // If the vertex has not yet been visited and the value is less than the 'MinValor'
- if( !visited[j] && matrix[j][0] < MinValue ){
- min = j; // Saves the position of the smallest
- MinValue = matrix[j][0]; // Save the smallest value
- }
- }
+ // The value 'i' from the for below is not used, as the for is only used to
+ // traverse the entire number of columns in the matrix
+ for (int i = 1; i < n; i++) { // Starts at 1 because you don't need to compare
+ // the vertex with itself
+
+ int min = -1; // Variable that stores the position of the smallest value,
+ // starts at -1 as it is an invalid position
+ unsigned long int MinValue =
+ 4294967295; // Variable that stores the smallest value found, starts
+ // with 'infinity', so always on the first pass the value
+ // will be smaller than this variable
+ // For that loops through all rows in column [0]
+ for (int j = 1; j < n; j++) {
+ // If the vertex has not yet been visited and the value is less than the
+ // 'MinValor'
+ if (!visited[j] && matrix[j][0] < MinValue) {
+ min = j; // Saves the position of the smallest
+ MinValue = matrix[j][0]; // Save the smallest value
+ }
+ }
- visited[min] = true; // Mark the value of the minimum position as visited
+ visited[min] = true; // Mark the value of the minimum position as visited
- // Goes from 1 to n
- for(int j = 1; j < n; j++){
- // If the value of column [0] + the value of the passing column is less than the value of the passing row and column [0]
- // Update the first column of the matrix, which will be used for the next iterations
- if( (matrix[min][0] + matrix[min][j]) < matrix[j][0] ){
- matrix[j][0] = matrix[min][0] + matrix[min][j];
- }
- }
+ // Goes from 1 to n
+ for (int j = 1; j < n; j++) {
+ // If the value of column [0] + the value of the passing column is less
+ // than the value of the passing row and column [0] Update the first
+ // column of the matrix, which will be used for the next iterations
+ if ((matrix[min][0] + matrix[min][j]) < matrix[j][0]) {
+ matrix[j][0] = matrix[min][0] + matrix[min][j];
+ }
}
+ }
}
-int main(){
+int main() {
- unsigned long int Matrix[noVertices][noVertices] = {{ 0, 6, 10, 4294967295, 4294967295 },
- { 6, 0, 4294967295, 2, 4294967295 },
- { 10, 4294967295, 0, 1, 3 },
- { 4294967295, 2, 1, 0, 8 },
- { 4294967295, 4294967295, 3, 8, 0 }};
+ unsigned long int Matrix[noVertices][noVertices] = {
+ {0, 6, 10, 4294967295, 4294967295},
+ {6, 0, 4294967295, 2, 4294967295},
+ {10, 4294967295, 0, 1, 3},
+ {4294967295, 2, 1, 0, 8},
+ {4294967295, 4294967295, 3, 8, 0}};
- Dijkstra(Matrix, noVertices);
+ Dijkstra(Matrix, noVertices);
- printf("Total shortest path from vertex 0 to 4: %lu\n", Matrix[4][0]); // Shortest total path
+ printf("Total shortest path from vertex 0 to 4: %lu\n",
+ Matrix[4][0]); // Shortest total path
- // Print the matrix with the updated values
- printf("Matrix:\n");
- for (int i = 0; i < noVertices; ++i){
- for (int e = 0; e < noVertices; ++e){
- if( Matrix[i][e] < 10 )
- printf(" %lu ", Matrix[i][e]);
- else
- printf("%lu ", Matrix[i][e]);
- }
- printf("\n");
+ // Print the matrix with the updated values
+ printf("Matrix:\n");
+ for (int i = 0; i < noVertices; ++i) {
+ for (int e = 0; e < noVertices; ++e) {
+ if (Matrix[i][e] < 10)
+ printf(" %lu ", Matrix[i][e]);
+ else
+ printf("%lu ", Matrix[i][e]);
}
printf("\n");
+ }
+ printf("\n");
- return 0;
+ return 0;
}
diff --git a/src/c/DoublyLinkedList.c b/src/c/DoublyLinkedList.c
index 1bf5cf3e..7be11ee4 100644
--- a/src/c/DoublyLinkedList.c
+++ b/src/c/DoublyLinkedList.c
@@ -1,7 +1,6 @@
/*
-* Exemplo Lista Duplamente Encadeada em C
-*/
-
+ * Exemplo Lista Duplamente Encadeada em C
+ */
#include
#include
@@ -9,149 +8,137 @@
/* Lista encadeada utilizando celula cabeça */
typedef struct cel celula;
-struct cel{
- int dado;
- struct cel *prox;
- struct cel *ant;
+struct cel {
+ int dado;
+ struct cel *prox;
+ struct cel *ant;
};
/* O ponteiro 'p' é a cabeça da lista*/
void insereInicio(int x, celula *p) /* Insere no inicio da lista*/
{
- celula *nova, *q;
- nova = malloc (sizeof (celula));
- nova->dado = x;
- nova->prox = p->prox;
- /* verifica se a lista está vazia*/
- if (p->prox != NULL)
- {
- q = nova->prox;
- q->ant = nova;
- }
- p->prox = nova;
- nova->ant = p;
+ celula *nova, *q;
+ nova = malloc(sizeof(celula));
+ nova->dado = x;
+ nova->prox = p->prox;
+ /* verifica se a lista está vazia*/
+ if (p->prox != NULL) {
+ q = nova->prox;
+ q->ant = nova;
+ }
+ p->prox = nova;
+ nova->ant = p;
}
void insereUltimo(int x, celula *p) /* Insere no final da lista*/
{
- celula *q;
- celula *nova;
- nova = malloc (sizeof (celula));
- nova->dado = x;
- q = p;
- while (q->prox != NULL)
- q = q->prox;
-
- q->prox = nova;
- nova->ant = q;
- nova->prox = NULL;
+ celula *q;
+ celula *nova;
+ nova = malloc(sizeof(celula));
+ nova->dado = x;
+ q = p;
+ while (q->prox != NULL)
+ q = q->prox;
+
+ q->prox = nova;
+ nova->ant = q;
+ nova->prox = NULL;
}
-
-void buscaEremove (int y, celula *p)
-{
- celula *w, *q;
- w = p;
- q = p->prox;
- while (q != NULL && q->dado != y) {
- w = q;
- q = q->prox;
- }
- if (q != NULL) {
- w->prox = q->prox;
- q->ant = w;
- free (q);
- }
- else{
- printf("\nLista nao contem item\n\n");
- system("pause");
- }
+void buscaEremove(int y, celula *p) {
+ celula *w, *q;
+ w = p;
+ q = p->prox;
+ while (q != NULL && q->dado != y) {
+ w = q;
+ q = q->prox;
+ }
+ if (q != NULL) {
+ w->prox = q->prox;
+ q->ant = w;
+ free(q);
+ } else {
+ printf("\nLista nao contem item\n\n");
+ system("pause");
+ }
}
-
-void imprime (celula *p)
-{
- celula *q;
- for (q = p->prox; q != NULL; q = q->prox)
- printf ("%d ", q->dado);
+void imprime(celula *p) {
+ celula *q;
+ for (q = p->prox; q != NULL; q = q->prox)
+ printf("%d ", q->dado);
}
-void Menu ()
-{
- printf(" Menu Principal\n");
- printf("1 - Insere inicio\n");
- printf("2 - Insere ultimo\n");
- printf("3 - Retira\n");
- printf("4 - Sair\n");
- printf("\nOpcao: ");
+void Menu() {
+ printf(" Menu Principal\n");
+ printf("1 - Insere inicio\n");
+ printf("2 - Insere ultimo\n");
+ printf("3 - Retira\n");
+ printf("4 - Sair\n");
+ printf("\nOpcao: ");
}
-void libera (celula *ini)
-{
- celula *p;
- p=ini;
- while (p != NULL) {
- celula *q = p->prox; /* guarda referência para o próximo elemento*/
- free(p); /* libera a memória apontada por p */
- p = q; /* faz p apontar para o próximo */
- }
+void libera(celula *ini) {
+ celula *p;
+ p = ini;
+ while (p != NULL) {
+ celula *q = p->prox; /* guarda referência para o próximo elemento*/
+ free(p); /* libera a memória apontada por p */
+ p = q; /* faz p apontar para o próximo */
+ }
}
+int main() {
+ celula *p;
+ int op = 0, item;
+ // inicializa lista
+ p = malloc(sizeof(celula));
+ p->ant = NULL;
+ p->prox = NULL;
+ // fim_inicializa
+
+ do {
+ system("cls");
+ printf("\nConteudo da lista: ");
+ if (p->prox != NULL) {
+ imprime(p);
+ } else {
+ printf("Lista VAZIA");
+ }
+ printf("\n\n");
+ Menu();
+ scanf("%d", &op);
+ switch (op) {
+ case 1:
+ printf("Insere no inicio da lista: ");
+ scanf("%d", &item);
+ insereInicio(item, p);
+ break;
+ case 2:
+ printf("Insere na ultima posicao da lista: ");
+ scanf("%d", &item);
+ insereUltimo(item, p);
+ break;
+ case 3:
+ if (p->prox != NULL) {
+ printf("Retirar um elemento: ");
+ scanf("%d", &item);
+ buscaEremove(item, p);
+ } else {
+ printf("\nLista VAZIA\n\n");
+ system("pause");
+ }
+ break;
+ case 4:
+ break;
+ default:
+ printf("Opcao invalida!\n");
+ system("pause");
+ break;
+ }
-int main()
-{
- celula *p;
- int op = 0,item;
- //inicializa lista
- p = malloc (sizeof (celula));
- p->ant = NULL;
- p->prox = NULL;
- //fim_inicializa
-
- do{
- system("cls");
- printf("\nConteudo da lista: ");
- if (p->prox != NULL){
- imprime(p);
- }
- else{
- printf("Lista VAZIA");
- }
- printf("\n\n");
- Menu();
- scanf("%d",&op);
- switch (op){
- case 1:
- printf("Insere no inicio da lista: ");
- scanf("%d",&item);
- insereInicio(item,p);
- break;
- case 2:
- printf("Insere na ultima posicao da lista: ");
- scanf("%d",&item);
- insereUltimo(item,p);
- break;
- case 3:
- if (p->prox != NULL){
- printf("Retirar um elemento: ");
- scanf("%d",&item);
- buscaEremove(item,p);
- }
- else{
- printf("\nLista VAZIA\n\n");
- system("pause");
- }
- break;
- case 4:
- break;
- default:
- printf("Opcao invalida!\n");
- system("pause");
- break;
- }
-
- }while(op!=4);
- libera(p);
- return 0;
+ } while (op != 4);
+ libera(p);
+ return 0;
}
diff --git a/src/c/DynamicQueue.c b/src/c/DynamicQueue.c
index 5b1d3711..074aebc6 100644
--- a/src/c/DynamicQueue.c
+++ b/src/c/DynamicQueue.c
@@ -1,72 +1,72 @@
/*
-* Implementação de uma Estrutura de Fila Dinâmica Ligada/Encadeada em C
-*/
+ * Implementação de uma Estrutura de Fila Dinâmica Ligada/Encadeada em C
+ */
-#include
#include
+#include
typedef int TIPOCHAVE;
-typedef struct NO{
- TIPOCHAVE chave;
- struct NO* prox;
-}*PONT;
+typedef struct NO {
+ TIPOCHAVE chave;
+ struct NO *prox;
+} *PONT;
-PONT novoNO(TIPOCHAVE ch){
- PONT aux = (PONT) malloc( sizeof(NO) );
- aux->chave = ch;
- aux->prox = NULL;
- return aux;
+PONT novoNO(TIPOCHAVE ch) {
+ PONT aux = (PONT)malloc(sizeof(NO));
+ aux->chave = ch;
+ aux->prox = NULL;
+ return aux;
}
-PONT insere(TIPOCHAVE ch, PONT no){
- PONT aux = novoNO(ch);
- aux->prox = no;
- return aux;
+PONT insere(TIPOCHAVE ch, PONT no) {
+ PONT aux = novoNO(ch);
+ aux->prox = no;
+ return aux;
}
-void mostraFila(PONT no){
- while(no != NULL){
- printf("[%d]->", no->chave);
- no = no->prox;
- }
- printf("\n");
+void mostraFila(PONT no) {
+ while (no != NULL) {
+ printf("[%d]->", no->chave);
+ no = no->prox;
+ }
+ printf("\n");
}
-void remove(PONT no){
- PONT noAnterior = no;
- while(no->prox != NULL){
- noAnterior = no;
- no = no->prox;
- }
- noAnterior->prox = NULL;
- free(no);
+void remove(PONT no) {
+ PONT noAnterior = no;
+ while (no->prox != NULL) {
+ noAnterior = no;
+ no = no->prox;
+ }
+ noAnterior->prox = NULL;
+ free(no);
}
-int tamanhoFila(PONT no){
- int cont = 0;
- while(no != NULL){
- cont++;
- no = no->prox;
- }
- return cont;
+int tamanhoFila(PONT no) {
+ int cont = 0;
+ while (no != NULL) {
+ cont++;
+ no = no->prox;
+ }
+ return cont;
}
-int main(){
- PONT fila = novoNO(5);
- fila = insere(8, fila);
- fila = insere(1, fila);
- fila = insere(3, fila);
- fila = insere(5, fila);
- fila = insere(4, fila);
- fila = insere(2, fila);
+int main() {
+ PONT fila = novoNO(5);
+ fila = insere(8, fila);
+ fila = insere(1, fila);
+ fila = insere(3, fila);
+ fila = insere(5, fila);
+ fila = insere(4, fila);
+ fila = insere(2, fila);
- mostraFila(fila);
- remove(fila);
- mostraFila(fila);
- remove(fila);
- mostraFila(fila);
+ mostraFila(fila);
+ remove(fila);
+ mostraFila(fila);
+ remove(fila);
+ mostraFila(fila);
- printf("Tamanho da fila: %d\n", tamanhoFila(fila) );
- return 0;
+ printf("Tamanho da fila: %d\n", tamanhoFila(fila));
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/DynamicStack.c b/src/c/DynamicStack.c
index f32a6dcd..4e63e575 100644
--- a/src/c/DynamicStack.c
+++ b/src/c/DynamicStack.c
@@ -1,82 +1,82 @@
/*
-* Pilha Dinâmica utilizando uma Lista Ligada em C
-*/
+ * Pilha Dinâmica utilizando uma Lista Ligada em C
+ */
-#include
#include
+#include
#define ERRO -1
typedef int TIPOCHAVE;
-typedef struct AUX{
- TIPOCHAVE chave;
- struct AUX *prox;
-}*PILHA;
+typedef struct AUX {
+ TIPOCHAVE chave;
+ struct AUX *prox;
+} *PILHA;
-PILHA CREATE(TIPOCHAVE ch){
- PILHA novaPilha = (PILHA) malloc( sizeof(PILHA) );
- novaPilha->chave = ch;
- novaPilha->prox = NULL;
- return novaPilha;
+PILHA CREATE(TIPOCHAVE ch) {
+ PILHA novaPilha = (PILHA)malloc(sizeof(PILHA));
+ novaPilha->chave = ch;
+ novaPilha->prox = NULL;
+ return novaPilha;
}
-PILHA PUSH(TIPOCHAVE ch, PILHA pi){
- /*while( pi->prox != NULL ){
- pi = pi->prox;
- }*/
- PILHA novo = CREATE(ch);
- //pi->prox = novo;
- novo->prox = pi;
- return novo;
+PILHA PUSH(TIPOCHAVE ch, PILHA pi) {
+ /*while( pi->prox != NULL ){
+ pi = pi->prox;
+ }*/
+ PILHA novo = CREATE(ch);
+ // pi->prox = novo;
+ novo->prox = pi;
+ return novo;
}
-PILHA POP(PILHA pi){
- PILHA sub = pi->prox;
- free(pi);
- return sub;
+PILHA POP(PILHA pi) {
+ PILHA sub = pi->prox;
+ free(pi);
+ return sub;
}
-void SHOW(PILHA pi){
- printf("PILHA:\n");
- while( pi->prox != NULL ){
- printf("[ %d ]\n", pi->chave);
- pi = pi->prox;
- }
- printf("[ %d ]\n", pi->chave);
+void SHOW(PILHA pi) {
+ printf("PILHA:\n");
+ while (pi->prox != NULL) {
+ printf("[ %d ]\n", pi->chave);
+ pi = pi->prox;
+ }
+ printf("[ %d ]\n", pi->chave);
}
-bool SEARCH(TIPOCHAVE ch, PILHA pi){
- bool vAchou = false;
- while(pi != NULL){
- if( pi->chave == ch )
- vAchou = true;
- pi = pi->prox;
- }
- return vAchou;
+bool SEARCH(TIPOCHAVE ch, PILHA pi) {
+ bool vAchou = false;
+ while (pi != NULL) {
+ if (pi->chave == ch)
+ vAchou = true;
+ pi = pi->prox;
+ }
+ return vAchou;
}
-int main(){
- PILHA vPilha;
-
- vPilha = PUSH(1, vPilha);
- vPilha = PUSH(2, vPilha);
- vPilha = PUSH(3, vPilha);
- vPilha = PUSH(4, vPilha);
- vPilha = PUSH(5, vPilha);
- vPilha = PUSH(6, vPilha);
-
- SHOW(vPilha);
-
- vPilha = POP(vPilha);
- vPilha = POP(vPilha);
-
- SHOW(vPilha);
-
- if( SEARCH(6, vPilha) )
- printf("\nAchou\n");
- else
- printf("\nNão achou\n");
-
- return 0;
+int main() {
+ PILHA vPilha;
+
+ vPilha = PUSH(1, vPilha);
+ vPilha = PUSH(2, vPilha);
+ vPilha = PUSH(3, vPilha);
+ vPilha = PUSH(4, vPilha);
+ vPilha = PUSH(5, vPilha);
+ vPilha = PUSH(6, vPilha);
+
+ SHOW(vPilha);
+
+ vPilha = POP(vPilha);
+ vPilha = POP(vPilha);
+
+ SHOW(vPilha);
+
+ if (SEARCH(6, vPilha))
+ printf("\nAchou\n");
+ else
+ printf("\nNão achou\n");
+
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/Exponentiation.c b/src/c/Exponentiation.c
index fb59d362..1abf4a77 100644
--- a/src/c/Exponentiation.c
+++ b/src/c/Exponentiation.c
@@ -1,24 +1,19 @@
-#include
+#include
+int exponenciacao(int base, int expoente) {
+ int i;
+ int result = base;
-int exponenciacao(int base, int expoente){
-
- int i;
- int result = base;
-
- for(i=0; i
+#include
+int exponenciacao(int base, int expoente) {
+ if (expoente == 0)
+ return 1;
-int exponenciacao(int base, int expoente){
-
- if(expoente==0) return 1;
-
- return (base * exponenciacao(base, expoente-1));
-
+ return (base * exponenciacao(base, expoente - 1));
}
+int main() {
+ printf("%d\n", exponenciacao(5, 3));
-int main(){
-
- printf("%d\n", exponenciacao(5, 3));
-
- return 0;
+ return 0;
}
diff --git a/src/c/Factorial.c b/src/c/Factorial.c
index 57dba9c7..bed39222 100644
--- a/src/c/Factorial.c
+++ b/src/c/Factorial.c
@@ -1,25 +1,25 @@
-#include
-#include
+#include
+#include
/*
-* Exemplos de função para retornar o fatorial de um número n
-* função recursiva
-*/
+ * Exemplos de função para retornar o fatorial de um número n
+ * função recursiva
+ */
-int main(){
- int num;
- printf("Digite um número: ");
- scanf("%d", &num);
- int result = fatorial(num);
- printf("1 => ");
- printf("%d! é : %d\n", num, result);
- return(0);
+int main() {
+ int num;
+ printf("Digite um número: ");
+ scanf("%d", &num);
+ int result = fatorial(num);
+ printf("1 => ");
+ printf("%d! é : %d\n", num, result);
+ return (0);
}
-int fatorial(int num){
- if(num <= 1 ){
- return 1;
- }
- printf("%d * ", num);
- return num * fatorial(num - 1);
+int fatorial(int num) {
+ if (num <= 1) {
+ return 1;
+ }
+ printf("%d * ", num);
+ return num * fatorial(num - 1);
}
diff --git a/src/c/FactorialRecursive.c b/src/c/FactorialRecursive.c
index a2390927..a4a2e4e6 100644
--- a/src/c/FactorialRecursive.c
+++ b/src/c/FactorialRecursive.c
@@ -1,20 +1,16 @@
-#include
+#include
+int fatorial(int n) {
+ if (n == 1)
+ return 1;
-int fatorial(int n){
-
- if(n==1) return 1;
-
- return (n * fatorial(n-1));
-
+ return (n * fatorial(n - 1));
}
+int main() {
+ printf("%d\n", fatorial(5));
-int main(){
-
- printf("%d\n", fatorial(5));
-
- return 0;
+ return 0;
}
diff --git a/src/c/FibonacciIterative.c b/src/c/FibonacciIterative.c
index 24177b90..36c7d1c1 100644
--- a/src/c/FibonacciIterative.c
+++ b/src/c/FibonacciIterative.c
@@ -1,18 +1,18 @@
#include
int fibonacci(int number) {
- int last_number = 0;
- int current_number = 1;
+ int last_number = 0;
+ int current_number = 1;
- for (int index = 0; index < number; ++index) {
- int temp = current_number;
- current_number += last_number;
- last_number = temp;
- }
- return last_number;
+ for (int index = 0; index < number; ++index) {
+ int temp = current_number;
+ current_number += last_number;
+ last_number = temp;
+ }
+ return last_number;
}
int main() {
- printf("Fibonacci Iterative: %d\n", fibonacci(12));
- return 0;
+ printf("Fibonacci Iterative: %d\n", fibonacci(12));
+ return 0;
}
diff --git a/src/c/FibonacciMemoization.c b/src/c/FibonacciMemoization.c
index 43cdaf9b..f8afb46b 100644
--- a/src/c/FibonacciMemoization.c
+++ b/src/c/FibonacciMemoization.c
@@ -1,27 +1,28 @@
#include
-#define MAX_N 100 // Define the maximum number for which you want to calculate Fibonacci
+#define MAX_N \
+ 100 // Define the maximum number for which you want to calculate Fibonacci
int memo[MAX_N]; // Memoization table to store computed values
int fibonacci(int number) {
- if (number <= 1) {
- return number;
- }
- if (memo[number] != -1) {
- return memo[number];
- }
-
- memo[number] = fibonacci(number - 1) + fibonacci(number - 2);
+ if (number <= 1) {
+ return number;
+ }
+ if (memo[number] != -1) {
return memo[number];
+ }
+
+ memo[number] = fibonacci(number - 1) + fibonacci(number - 2);
+ return memo[number];
}
int main(void) {
- // Initialize the memoization table with -1 (uncomputed)
- for (int i = 0; i < MAX_N; i++) {
- memo[i] = -1;
- }
+ // Initialize the memoization table with -1 (uncomputed)
+ for (int i = 0; i < MAX_N; i++) {
+ memo[i] = -1;
+ }
- printf("memoization: %d\n", fibonacci(12));
- return 0;
+ printf("memoization: %d\n", fibonacci(12));
+ return 0;
}
diff --git a/src/c/FibonacciRecursive.c b/src/c/FibonacciRecursive.c
index ecaff406..1054cc06 100644
--- a/src/c/FibonacciRecursive.c
+++ b/src/c/FibonacciRecursive.c
@@ -1,18 +1,18 @@
#include
int fibonacci(int number) {
- if (number == 0) {
- return 0;
- } else if (number == 1) {
- return 1;
- } else {
- return fibonacci(number - 1) + fibonacci(number - 2);
- }
+ if (number == 0) {
+ return 0;
+ } else if (number == 1) {
+ return 1;
+ } else {
+ return fibonacci(number - 1) + fibonacci(number - 2);
+ }
}
int main(void) {
- int test_nbr = 12;
+ int test_nbr = 12;
- printf("recursive: %d\n", fibonacci(test_nbr));
- return 0;
+ printf("recursive: %d\n", fibonacci(test_nbr));
+ return 0;
}
diff --git a/src/c/FloydWarshall.c b/src/c/FloydWarshall.c
index b6c6b68c..1ce22edc 100644
--- a/src/c/FloydWarshall.c
+++ b/src/c/FloydWarshall.c
@@ -1,85 +1,90 @@
/*
-* Grafos - Algoritmo de Floyd-Warshall em C
-* Complexidade: Teta de vértices ao cubo = Teta(n^3)
-*
-* Encontra o caminho de todos para todos os vértices
-*
-* Grafo com 5 vértices e 6 arestas
-*
-* 6
-* (0)-----------------(1)
-* | |
-* 10 | | 2
-* | 1 |
-* (2)-----------------(3)
-* \ /
-* 3 \ / 8
-* \ /
-* -----(4)-----
-*
-* Matriz de Distância
-* 0 1 2 3 4
-* 0 0 6 10 - -
-* 1 6 0 - 2 -
-* 2 10 - 0 1 3
-* 3 - 2 1 0 8
-* 4 - - 3 8 0
-*
-* Para valores infinitos será considerado o valor: 4294967295
-*
-*/
+ * Grafos - Algoritmo de Floyd-Warshall em C
+ * Complexidade: Teta de vértices ao cubo = Teta(n^3)
+ *
+ * Encontra o caminho de todos para todos os vértices
+ *
+ * Grafo com 5 vértices e 6 arestas
+ *
+ * 6
+ * (0)-----------------(1)
+ * | |
+ * 10 | | 2
+ * | 1 |
+ * (2)-----------------(3)
+ * \ /
+ * 3 \ / 8
+ * \ /
+ * -----(4)-----
+ *
+ * Matriz de Distância
+ * 0 1 2 3 4
+ * 0 0 6 10 - -
+ * 1 6 0 - 2 -
+ * 2 10 - 0 1 3
+ * 3 - 2 1 0 8
+ * 4 - - 3 8 0
+ *
+ * Para valores infinitos será considerado o valor: 4294967295
+ *
+ */
#include
-#define nroVertices 5 // Define uma constante 5 que é a quantidade de vértices do grafo
+#define nroVertices \
+ 5 // Define uma constante 5 que é a quantidade de vértices do grafo
-// Algoritmo de Floyd-Warshall recebe como parâmetro a matriz de distância e o número de vértices
-void FloydWarshall(unsigned long int matriz[nroVertices][nroVertices], int n){
- for(int x = 0; x < n; x++){
- for(int y = 0; y < n; y++){
- for(int z = 0; z < n; z++){
- if( matriz[y][z] > (matriz[y][x] + matriz[x][z]) )
- matriz[y][z] = matriz[y][x] + matriz[x][z];
- }
- }
- }
+// Algoritmo de Floyd-Warshall recebe como parâmetro a matriz de distância e o
+// número de vértices
+void FloydWarshall(unsigned long int matriz[nroVertices][nroVertices], int n) {
+ for (int x = 0; x < n; x++) {
+ for (int y = 0; y < n; y++) {
+ for (int z = 0; z < n; z++) {
+ if (matriz[y][z] > (matriz[y][x] + matriz[x][z]))
+ matriz[y][z] = matriz[y][x] + matriz[x][z];
+ }
+ }
+ }
}
-int main(){
+int main() {
- unsigned long int Matriz[nroVertices][nroVertices] = {{ 0, 6, 10, 4294967295, 4294967295 },
- { 6, 0, 4294967295, 2, 4294967295 },
- { 10, 4294967295, 0, 1, 3 },
- { 4294967295, 2, 1, 0, 8 },
- { 4294967295, 4294967295, 3, 8, 0 }};
+ unsigned long int Matriz[nroVertices][nroVertices] = {
+ {0, 6, 10, 4294967295, 4294967295},
+ {6, 0, 4294967295, 2, 4294967295},
+ {10, 4294967295, 0, 1, 3},
+ {4294967295, 2, 1, 0, 8},
+ {4294967295, 4294967295, 3, 8, 0}};
- FloydWarshall(Matriz, nroVertices);
+ FloydWarshall(Matriz, nroVertices);
- // Mostra a matriz com os valores atualizados
- printf("Matriz:\n");
- for (int i = 0; i < nroVertices; ++i){
- for (int e = 0; e < nroVertices; ++e){
- if( Matriz[i][e] < 10 )
- printf(" %lu ", Matriz[i][e]);
- else
- printf("%lu ", Matriz[i][e]);
- }
- printf("\n");
- }
- printf("\n");
+ // Mostra a matriz com os valores atualizados
+ printf("Matriz:\n");
+ for (int i = 0; i < nroVertices; ++i) {
+ for (int e = 0; e < nroVertices; ++e) {
+ if (Matriz[i][e] < 10)
+ printf(" %lu ", Matriz[i][e]);
+ else
+ printf("%lu ", Matriz[i][e]);
+ }
+ printf("\n");
+ }
+ printf("\n");
- //printf("Total caminho mais curto do vertice 0 ao 4: %lu\n", Matriz[4][0]); // [destino] [origem]
- //printf("Total caminho mais curto do vertice 2 ao 0: %lu\n", Matriz[0][2]);
- //printf("Total caminho mais curto do vertice 4 ao 3: %lu\n\n", Matriz[3][4]);
+ // printf("Total caminho mais curto do vertice 0 ao 4: %lu\n", Matriz[4][0]);
+ // // [destino] [origem] printf("Total caminho mais curto do vertice 2 ao 0:
+ // %lu\n", Matriz[0][2]); printf("Total caminho mais curto do vertice 4 ao 3:
+ // %lu\n\n", Matriz[3][4]);
- // Mostra todos os caminhos
- printf("\n");
- for (int i = 0; i < nroVertices; ++i){
- for (int x = 0; x < nroVertices; ++x){
- printf("Menor distancia saindo do %d para chegar ao %d = %lu.\n", i, x, Matriz[x][i]);
- }
- }
- printf("\n\n");
+ // Mostra todos os caminhos
+ printf("\n");
+ for (int i = 0; i < nroVertices; ++i) {
+ for (int x = 0; x < nroVertices; ++x) {
+ printf("Menor distancia saindo do %d para chegar ao %d = %lu.\n", i, x,
+ Matriz[x][i]);
+ }
+ }
+ printf("\n\n");
- return 0;
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/GraphSearch.c b/src/c/GraphSearch.c
index 2bfe7708..7679dce2 100644
--- a/src/c/GraphSearch.c
+++ b/src/c/GraphSearch.c
@@ -1,203 +1,225 @@
/*
-*
-* Grafos - Implementação de uma estrutura de Grafo não dirigido em C
-* Métodos de Busca: Busca em Profundidade e Busca em Largura
-*
-*
-* (A)---------------(B)-------------(E)---------------(F)
-* | | | |
-* | | | |
-* | | | |
-* (C)---------------(D)--------------- |
-* | |
-* -----------------------------------
-*
-* 6 Vértices
-* 8 Arestas
-*/
+ *
+ * Grafos - Implementação de uma estrutura de Grafo não dirigido em C
+ * Métodos de Busca: Busca em Profundidade e Busca em Largura
+ *
+ *
+ * (A)---------------(B)-------------(E)---------------(F)
+ * | | | |
+ * | | | |
+ * | | | |
+ * (C)---------------(D)--------------- |
+ * | |
+ * -----------------------------------
+ *
+ * 6 Vértices
+ * 8 Arestas
+ */
-#include
#include
+#include
-#define MAX_VERTICES 6 // MÁXIMO DE VÉRTICES DO GRAFO, SE FOR ALTERAR O GRAFO PRECISA ALTERAR ESTA VARIÁVEL TAMBÉM
-#define MAX_ARESTAS (MAX_VERTICES * (MAX_VERTICES-1)) // CALCULA O NÚMERO MÁXIMO DE ARESTAS QUE O GRAFO PODERÁ TER
+#define MAX_VERTICES \
+ 6 // MÁXIMO DE VÉRTICES DO GRAFO, SE FOR ALTERAR O GRAFO PRECISA ALTERAR ESTA
+ // VARIÁVEL TAMBÉM
+#define MAX_ARESTAS \
+ (MAX_VERTICES * \
+ (MAX_VERTICES - \
+ 1)) // CALCULA O NÚMERO MÁXIMO DE ARESTAS QUE O GRAFO PODERÁ TER
// Estrutura que define cada Vértice do Grafo
-typedef struct NO{
- char id;
- int nroVizinhos;
- struct NO* vizinhos[MAX_ARESTAS];
- bool visitado;
-}*VERTICE;
+typedef struct NO {
+ char id;
+ int nroVizinhos;
+ struct NO *vizinhos[MAX_ARESTAS];
+ bool visitado;
+} *VERTICE;
// Cria Vértice e retorna
-VERTICE criaVertice(char id){
- VERTICE novoVertice = (VERTICE) malloc( sizeof(NO) ); // Aloca um novo Vértice
- novoVertice->id = id;
- novoVertice->nroVizinhos = 0;
- novoVertice->visitado = false;
- for (int i = 0; i < MAX_ARESTAS; i++){
- novoVertice->vizinhos[i] = NULL;
- }
- return novoVertice;
+VERTICE criaVertice(char id) {
+ VERTICE novoVertice = (VERTICE)malloc(sizeof(NO)); // Aloca um novo Vértice
+ novoVertice->id = id;
+ novoVertice->nroVizinhos = 0;
+ novoVertice->visitado = false;
+ for (int i = 0; i < MAX_ARESTAS; i++) {
+ novoVertice->vizinhos[i] = NULL;
+ }
+ return novoVertice;
}
// Liga os vértices passados como parâmetro
-bool ligaVertices(VERTICE v1, VERTICE v2){
- int aux = 0;
- while(v1->vizinhos[aux] != NULL){ // Busca a primeira posição 'vazia'(NULL) dos vizinhos
- aux++;
- }
- v1->vizinhos[aux] = v2; // Adiciona o novo vizinho a lista de vizinhos
- aux = 0;
- while(v2->vizinhos[aux] != NULL){ // Busca a primeira posição 'vazia'(NULL) dos vizinhos
- aux++;
- }
- v2->vizinhos[aux] = v1; // Adiciona o novo vizinho a lista de vizinhos
- v1->nroVizinhos++; // Incrementa o número de vizinhos
- v2->nroVizinhos++; // Incrementa o número de vizinhos
+bool ligaVertices(VERTICE v1, VERTICE v2) {
+ int aux = 0;
+ while (v1->vizinhos[aux] !=
+ NULL) { // Busca a primeira posição 'vazia'(NULL) dos vizinhos
+ aux++;
+ }
+ v1->vizinhos[aux] = v2; // Adiciona o novo vizinho a lista de vizinhos
+ aux = 0;
+ while (v2->vizinhos[aux] !=
+ NULL) { // Busca a primeira posição 'vazia'(NULL) dos vizinhos
+ aux++;
+ }
+ v2->vizinhos[aux] = v1; // Adiciona o novo vizinho a lista de vizinhos
+ v1->nroVizinhos++; // Incrementa o número de vizinhos
+ v2->nroVizinhos++; // Incrementa o número de vizinhos
}
/*
-* Busca em Profundidade - DFS - Depht First Search
-* Percorre primeiro todos os vizinhos que foram ligados primeiro ao vértice
-*
-*/
-int buscaEmProfundidade(VERTICE inicio, VERTICE destino, int visitados){
- inicio->visitado = true; // Marca o Vértice que está passando inicio como já visitado
- if( inicio == destino ) return visitados; // Se for o buscado (destino) retorna ele
-
- int aux = 0;
- while( inicio->vizinhos[aux] != NULL ){ // Enquanto existe vizinhos a serem visitados
- if( inicio->vizinhos[aux]->visitado == false ){ // Se o vizinho ainda não foi visitado
- // Chama recursivamente passando novo vizinho como iniício, ou seja, irá percorrer todos os vizinhos dele, e assim, sucessivamente
- int resposta = buscaEmProfundidade(inicio->vizinhos[aux], destino, visitados+1);
- // Se o retorno for maior que -1 então é porque encontrou, sendo assim, já retorna a resposta
- if( resposta != -1 ) return resposta;
- }
- aux++; // Incrementa 1 na lista de vizinhos
- }
-
- return -1; // Não encontrou o vértice
+ * Busca em Profundidade - DFS - Depht First Search
+ * Percorre primeiro todos os vizinhos que foram ligados primeiro ao
+ *vértice
+ *
+ */
+int buscaEmProfundidade(VERTICE inicio, VERTICE destino, int visitados) {
+ inicio->visitado =
+ true; // Marca o Vértice que está passando inicio como já visitado
+ if (inicio == destino)
+ return visitados; // Se for o buscado (destino) retorna ele
+
+ int aux = 0;
+ while (inicio->vizinhos[aux] !=
+ NULL) { // Enquanto existe vizinhos a serem visitados
+ if (inicio->vizinhos[aux]->visitado ==
+ false) { // Se o vizinho ainda não foi visitado
+ // Chama recursivamente passando novo vizinho como iniício, ou seja, irá
+ // percorrer todos os vizinhos dele, e assim, sucessivamente
+ int resposta =
+ buscaEmProfundidade(inicio->vizinhos[aux], destino, visitados + 1);
+ // Se o retorno for maior que -1 então é porque encontrou, sendo assim, já
+ // retorna a resposta
+ if (resposta != -1)
+ return resposta;
+ }
+ aux++; // Incrementa 1 na lista de vizinhos
+ }
+
+ return -1; // Não encontrou o vértice
}
/*
-* Busca em Largura - BFS - Breadth First Search
-* Implementada com o conceito de fila, porém utilizando um array simples
-* Assim ela não excluí o 'vértice' do array, apenas pula uma posição para a frente
-* Percorre todos os vértices por nível
-*/
-int buscaEmLargura(VERTICE inicio, VERTICE destino){
- int iniFila = 0; // Variável que controla a posição do inicio da fila, é utilizada para controlar o WHILE
- int tamFila = 1; // Variável que controla o tamanho da fila
-
- VERTICE FILA[MAX_VERTICES]; // Fila que irá guardar os vértices a serem comparados
- for (int i = 0; i < MAX_VERTICES; i++){ // Como a lista não é dinâmica, ela precisa ser 'limpa' primeiro
- FILA[i] = NULL;
- }
- FILA[iniFila] = inicio; // Posição [0] da fila recebe o vértice de início
-
- // Enquanto não terminar a fila faça
- while( iniFila < tamFila ){
- // Se o elemento que está para 'sair' da fila for o buscado (destino) então retorna iniFila, que foi a distância percorrida para encontrar
- if( FILA[iniFila] == destino ) return iniFila;
-
- /*
- * Para todos os vizinhos do vértice que está para 'sair' da fila:
- * Marca todos como visitado, para não coloca-los na fila novamente,
- * e então os coloca na fila, e aumenta o tamanho da fila
- */
- for (int i = 0; i < FILA[iniFila]->nroVizinhos; i++){
- if( FILA[iniFila]->vizinhos[i]->visitado == false ){
- FILA[iniFila]->vizinhos[i]->visitado = true;
- FILA[tamFila] = FILA[iniFila]->vizinhos[i];
- tamFila++;
- }
- }
- iniFila++; // Incrementa 1 no inicio da fila, como se tivesse excluído o primeiro que entrou na fila (FIFO - First In First Out)
- }
- return -1;
+ * Busca em Largura - BFS - Breadth First Search
+ * Implementada com o conceito de fila, porém utilizando um array simples
+ * Assim ela não excluí o 'vértice' do array, apenas pula uma posição para
+ *a frente Percorre todos os vértices por nível
+ */
+int buscaEmLargura(VERTICE inicio, VERTICE destino) {
+ int iniFila = 0; // Variável que controla a posição do inicio da fila, é
+ // utilizada para controlar o WHILE
+ int tamFila = 1; // Variável que controla o tamanho da fila
+
+ VERTICE
+ FILA[MAX_VERTICES]; // Fila que irá guardar os vértices a serem comparados
+ for (int i = 0; i < MAX_VERTICES;
+ i++) { // Como a lista não é dinâmica, ela precisa ser 'limpa' primeiro
+ FILA[i] = NULL;
+ }
+ FILA[iniFila] = inicio; // Posição [0] da fila recebe o vértice de início
+
+ // Enquanto não terminar a fila faça
+ while (iniFila < tamFila) {
+ // Se o elemento que está para 'sair' da fila for o buscado (destino) então
+ // retorna iniFila, que foi a distância percorrida para encontrar
+ if (FILA[iniFila] == destino)
+ return iniFila;
+
+ /*
+ * Para todos os vizinhos do vértice que está para 'sair' da fila:
+ * Marca todos como visitado, para não coloca-los na fila novamente,
+ * e então os coloca na fila, e aumenta o tamanho da fila
+ */
+ for (int i = 0; i < FILA[iniFila]->nroVizinhos; i++) {
+ if (FILA[iniFila]->vizinhos[i]->visitado == false) {
+ FILA[iniFila]->vizinhos[i]->visitado = true;
+ FILA[tamFila] = FILA[iniFila]->vizinhos[i];
+ tamFila++;
+ }
+ }
+ iniFila++; // Incrementa 1 no inicio da fila, como se tivesse excluído o
+ // primeiro que entrou na fila (FIFO - First In First Out)
+ }
+ return -1;
}
-int main(){
-
- // Grafo conjunto de vértices independentes
- VERTICE A = criaVertice('A');
- VERTICE B = criaVertice('B');
- VERTICE C = criaVertice('C');
- VERTICE D = criaVertice('D');
- VERTICE E = criaVertice('E');
- VERTICE F = criaVertice('F');
-
- // Liga todos os vértices de acordo com o GRAFO apresentado na introdução
- ligaVertices(A, B);
- ligaVertices(A, C);
- ligaVertices(B, D);
- ligaVertices(C, D);
- ligaVertices(B, E);
- ligaVertices(D, E);
- ligaVertices(E, F);
- ligaVertices(D, F);
-
- // Realiza a busca em profundidade
- int res = buscaEmProfundidade(A, F, 0);
- if( res != -1 )
- printf("DFS - Encontrou. Distancia: %d.\n", res);
- else
- printf("DFS - Não encontrou.\n");
-
- // 'Zera' todos os atributos 'visitado' de todos os vértices para 'false'
- A->visitado = false;
- B->visitado = false;
- C->visitado = false;
- D->visitado = false;
- E->visitado = false;
- F->visitado = false;
-
- // Realiza a busca em largura
- res = buscaEmLargura(A, F);
- if( res != -1 )
- printf("BFS - Encontrou. Distancia: %d.\n", res);
- else
- printf("BFS - Não encontrou.\n");
-
- // Grafo conjunto de vértices em um array
- VERTICE GRAFO[MAX_VERTICES];
- GRAFO[0] = criaVertice('A');
- GRAFO[1] = criaVertice('B');
- GRAFO[2] = criaVertice('C');
- GRAFO[3] = criaVertice('D');
- GRAFO[4] = criaVertice('E');
- GRAFO[5] = criaVertice('F');
-
- // Liga todos os vértices de acordo com o GRAFO apresentado na introdução
- ligaVertices(GRAFO[0], GRAFO[1]);
- ligaVertices(GRAFO[0], GRAFO[2]);
- ligaVertices(GRAFO[1], GRAFO[3]);
- ligaVertices(GRAFO[2], GRAFO[3]);
- ligaVertices(GRAFO[1], GRAFO[4]);
- ligaVertices(GRAFO[3], GRAFO[4]);
- ligaVertices(GRAFO[4], GRAFO[5]);
- ligaVertices(GRAFO[3], GRAFO[5]);
-
- // Realiza a busca em profundidade
- res = buscaEmProfundidade(GRAFO[0], GRAFO[5], 0);
- if( res != -1 )
- printf("DFS - Encontrou. Distancia: %d.\n", res);
- else
- printf("DFS - Não encontrou.\n");
-
- // 'Zera' todos os atributos 'visitado' de todos os vértices para 'false'
- for (int i = 0; i < MAX_VERTICES; i++){
- GRAFO[i]->visitado = false;
- }
-
- // Realiza a busca em largura
- res = buscaEmLargura(GRAFO[0], GRAFO[5]);
- if( res != -1 )
- printf("BFS - Encontrou. Distancia: %d.\n", res);
- else
- printf("BFS - Não encontrou.\n");
-
- return 0;
+int main() {
+
+ // Grafo conjunto de vértices independentes
+ VERTICE A = criaVertice('A');
+ VERTICE B = criaVertice('B');
+ VERTICE C = criaVertice('C');
+ VERTICE D = criaVertice('D');
+ VERTICE E = criaVertice('E');
+ VERTICE F = criaVertice('F');
+
+ // Liga todos os vértices de acordo com o GRAFO apresentado na introdução
+ ligaVertices(A, B);
+ ligaVertices(A, C);
+ ligaVertices(B, D);
+ ligaVertices(C, D);
+ ligaVertices(B, E);
+ ligaVertices(D, E);
+ ligaVertices(E, F);
+ ligaVertices(D, F);
+
+ // Realiza a busca em profundidade
+ int res = buscaEmProfundidade(A, F, 0);
+ if (res != -1)
+ printf("DFS - Encontrou. Distancia: %d.\n", res);
+ else
+ printf("DFS - Não encontrou.\n");
+
+ // 'Zera' todos os atributos 'visitado' de todos os vértices para 'false'
+ A->visitado = false;
+ B->visitado = false;
+ C->visitado = false;
+ D->visitado = false;
+ E->visitado = false;
+ F->visitado = false;
+
+ // Realiza a busca em largura
+ res = buscaEmLargura(A, F);
+ if (res != -1)
+ printf("BFS - Encontrou. Distancia: %d.\n", res);
+ else
+ printf("BFS - Não encontrou.\n");
+
+ // Grafo conjunto de vértices em um array
+ VERTICE GRAFO[MAX_VERTICES];
+ GRAFO[0] = criaVertice('A');
+ GRAFO[1] = criaVertice('B');
+ GRAFO[2] = criaVertice('C');
+ GRAFO[3] = criaVertice('D');
+ GRAFO[4] = criaVertice('E');
+ GRAFO[5] = criaVertice('F');
+
+ // Liga todos os vértices de acordo com o GRAFO apresentado na introdução
+ ligaVertices(GRAFO[0], GRAFO[1]);
+ ligaVertices(GRAFO[0], GRAFO[2]);
+ ligaVertices(GRAFO[1], GRAFO[3]);
+ ligaVertices(GRAFO[2], GRAFO[3]);
+ ligaVertices(GRAFO[1], GRAFO[4]);
+ ligaVertices(GRAFO[3], GRAFO[4]);
+ ligaVertices(GRAFO[4], GRAFO[5]);
+ ligaVertices(GRAFO[3], GRAFO[5]);
+
+ // Realiza a busca em profundidade
+ res = buscaEmProfundidade(GRAFO[0], GRAFO[5], 0);
+ if (res != -1)
+ printf("DFS - Encontrou. Distancia: %d.\n", res);
+ else
+ printf("DFS - Não encontrou.\n");
+
+ // 'Zera' todos os atributos 'visitado' de todos os vértices para 'false'
+ for (int i = 0; i < MAX_VERTICES; i++) {
+ GRAFO[i]->visitado = false;
+ }
+
+ // Realiza a busca em largura
+ res = buscaEmLargura(GRAFO[0], GRAFO[5]);
+ if (res != -1)
+ printf("BFS - Encontrou. Distancia: %d.\n", res);
+ else
+ printf("BFS - Não encontrou.\n");
+
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/Graphs.c b/src/c/Graphs.c
index bd46e85a..85495e11 100644
--- a/src/c/Graphs.c
+++ b/src/c/Graphs.c
@@ -1,125 +1,126 @@
/*
-*
-*
-* ---------------------
-* | |
-* | |
-* 5 V 8 |
-* (A)------------->(B)------------ | 2
-* \ | |
-* \ | |
-* \ 6 4 V |
-* ---------->(C)--------->(D)------
-*
-*
-*/
+ *
+ *
+ * ---------------------
+ * | |
+ * | |
+ * 5 V 8 |
+ * (A)------------->(B)------------ | 2
+ * \ | |
+ * \ | |
+ * \ 6 4 V |
+ * ---------->(C)--------->(D)------
+ *
+ *
+ */
-#include
#include
+#include
-#define MAX_VERTICES 20 // Constante que define o máximo de vertices que o grafo pode ter
+#define MAX_VERTICES \
+ 20 // Constante que define o máximo de vertices que o grafo pode ter
-int nroVertices = 0; // Guarda o número de vértices atual
+int nroVertices = 0; // Guarda o número de vértices atual
int matriz[MAX_VERTICES][MAX_VERTICES]; // Matriz de Distancia
int componentes;
-typedef struct NO{
- char id;
- int nroVizinhos;
- struct AUX* vizinhos[];
- bool visitado;
- int indice; // Guarda a ordem em que o vértice foi criado
-}*VERTICE;
-
-typedef struct AUX{
- VERTICE vizinho;
- int valor;
-}*ARESTA;
-
-VERTICE criaVertice(char id){
- matriz[nroVertices][nroVertices] = 0;
- VERTICE novo = (VERTICE) malloc( sizeof(NO) );
- novo->id = id;
- novo->nroVizinhos = 0;
- novo->visitado = false;
- novo->indice = nroVertices;
- nroVertices++;
- return novo;
+typedef struct NO {
+ char id;
+ int nroVizinhos;
+ struct AUX *vizinhos[];
+ bool visitado;
+ int indice; // Guarda a ordem em que o vértice foi criado
+} *VERTICE;
+
+typedef struct AUX {
+ VERTICE vizinho;
+ int valor;
+} *ARESTA;
+
+VERTICE criaVertice(char id) {
+ matriz[nroVertices][nroVertices] = 0;
+ VERTICE novo = (VERTICE)malloc(sizeof(NO));
+ novo->id = id;
+ novo->nroVizinhos = 0;
+ novo->visitado = false;
+ novo->indice = nroVertices;
+ nroVertices++;
+ return novo;
}
-void ligaVertice(VERTICE v1, VERTICE v2, int valor){
- matriz[v1->indice][v2->indice] = valor;
- ARESTA nova = (ARESTA) malloc( sizeof(AUX) );
- nova->vizinho = v2;
- nova->valor = valor;
- v1->vizinhos[v1->nroVizinhos] = nova;
- v1->nroVizinhos++;
+void ligaVertice(VERTICE v1, VERTICE v2, int valor) {
+ matriz[v1->indice][v2->indice] = valor;
+ ARESTA nova = (ARESTA)malloc(sizeof(AUX));
+ nova->vizinho = v2;
+ nova->valor = valor;
+ v1->vizinhos[v1->nroVizinhos] = nova;
+ v1->nroVizinhos++;
}
-void mostraMatrizDistancia(){
- printf("\nMatriz de Distancia\n");
- for(int l = 0; l < nroVertices; l++){
- for(int c = 0; c < nroVertices; c++){
- if( matriz[l][c] == -1 )
- printf("%d, ", matriz[l][c]);
- else
- printf(" %d, ", matriz[l][c]);
- }
- printf("\n");
- }
- printf("\n");
+void mostraMatrizDistancia() {
+ printf("\nMatriz de Distancia\n");
+ for (int l = 0; l < nroVertices; l++) {
+ for (int c = 0; c < nroVertices; c++) {
+ if (matriz[l][c] == -1)
+ printf("%d, ", matriz[l][c]);
+ else
+ printf(" %d, ", matriz[l][c]);
+ }
+ printf("\n");
+ }
+ printf("\n");
}
-void zeraVariaveis(){
- for(int l = 0; l < MAX_VERTICES; l++){
- for(int c = 0; c < MAX_VERTICES; c++){
- matriz[l][c] = -1;
- }
- }
+void zeraVariaveis() {
+ for (int l = 0; l < MAX_VERTICES; l++) {
+ for (int c = 0; c < MAX_VERTICES; c++) {
+ matriz[l][c] = -1;
+ }
+ }
}
-void visitaVizinhos(bool visitados[], int atual){
- for (int i = 0; i < nroVertices; i++){
- if( visitados[i] == false && matriz[atual][i] > 0 ){
- visitados[i] = true;
- componentes++;
- visitaVizinhos(visitados, i);
- }
- }
+void visitaVizinhos(bool visitados[], int atual) {
+ for (int i = 0; i < nroVertices; i++) {
+ if (visitados[i] == false && matriz[atual][i] > 0) {
+ visitados[i] = true;
+ componentes++;
+ visitaVizinhos(visitados, i);
+ }
+ }
}
-void calculaComponentesConexos(){
- bool visitados[nroVertices];
- for (int i = 0; i < nroVertices; ++i){
- visitados[i] = false;
- }
- for (int i = 0; i < nroVertices; i++){
- if( visitados[i] == false ){
- visitaVizinhos(visitados, i);
- }
- }
+void calculaComponentesConexos() {
+ bool visitados[nroVertices];
+ for (int i = 0; i < nroVertices; ++i) {
+ visitados[i] = false;
+ }
+ for (int i = 0; i < nroVertices; i++) {
+ if (visitados[i] == false) {
+ visitaVizinhos(visitados, i);
+ }
+ }
}
-int main(){
- zeraVariaveis();
-
- // Matriz de Distância funciona conforme a ordem inserida
- VERTICE A = criaVertice('A');
- VERTICE B = criaVertice('B');
- VERTICE C = criaVertice('C');
- VERTICE D = criaVertice('D');
- VERTICE E = criaVertice('E');
-
- ligaVertice(A, B, 5);
- ligaVertice(A, C, 6);
- ligaVertice(B, D, 8);
- ligaVertice(C, D, 4);
- ligaVertice(D, B, 2);
-
- calculaComponentesConexos();
- printf("\nComponentes Conexos: %d\n", componentes) ;
-
- mostraMatrizDistancia();
-
- return 0;
+int main() {
+ zeraVariaveis();
+
+ // Matriz de Distância funciona conforme a ordem inserida
+ VERTICE A = criaVertice('A');
+ VERTICE B = criaVertice('B');
+ VERTICE C = criaVertice('C');
+ VERTICE D = criaVertice('D');
+ VERTICE E = criaVertice('E');
+
+ ligaVertice(A, B, 5);
+ ligaVertice(A, C, 6);
+ ligaVertice(B, D, 8);
+ ligaVertice(C, D, 4);
+ ligaVertice(D, B, 2);
+
+ calculaComponentesConexos();
+ printf("\nComponentes Conexos: %d\n", componentes);
+
+ mostraMatrizDistancia();
+
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/HamiltonianCycle.c b/src/c/HamiltonianCycle.c
index f54c950c..aea872f6 100644
--- a/src/c/HamiltonianCycle.c
+++ b/src/c/HamiltonianCycle.c
@@ -1,133 +1,143 @@
/*
-*
-* Grafos - CICLO HAMILTONIANO em C
-*
-* -----------------------------------
-* | |
-* (A)---------------(B)-------------(E)---------------(F)
-* | | | |
-* | | | |
-* | | | |
-* (C)---------------(D)--------------- |
-* | |
-* -----------------------------------
-*
-* 6 Vértices
-* 9 Arestas
-*/
+ *
+ * Grafos - CICLO HAMILTONIANO em C
+ *
+ * -----------------------------------
+ * | |
+ * (A)---------------(B)-------------(E)---------------(F)
+ * | | | |
+ * | | | |
+ * | | | |
+ * (C)---------------(D)--------------- |
+ * | |
+ * -----------------------------------
+ *
+ * 6 Vértices
+ * 9 Arestas
+ */
-#include
#include
+#include
-#define MAX_VERTICES 6 // MÁXIMO DE VÉRTICES DO GRAFO, SE FOR ALTERAR O GRAFO PRECISA ALTERAR ESTA VARIÁVEL TAMBÉM
-#define MAX_ARESTAS (MAX_VERTICES * (MAX_VERTICES-1)) // CALCULA O NÚMERO MÁXIMO DE ARESTAS QUE O GRAFO PODERÁ TER
+#define MAX_VERTICES \
+ 6 // MÁXIMO DE VÉRTICES DO GRAFO, SE FOR ALTERAR O GRAFO PRECISA ALTERAR ESTA
+ // VARIÁVEL TAMBÉM
+#define MAX_ARESTAS \
+ (MAX_VERTICES * \
+ (MAX_VERTICES - \
+ 1)) // CALCULA O NÚMERO MÁXIMO DE ARESTAS QUE O GRAFO PODERÁ TER
// Estrutura que define cada Vértice do Grafo
-typedef struct NO{
- char id;
- int nroVizinhos;
- struct NO* vizinhos[MAX_ARESTAS];
- bool visitado;
-}*VERTICE;
+typedef struct NO {
+ char id;
+ int nroVizinhos;
+ struct NO *vizinhos[MAX_ARESTAS];
+ bool visitado;
+} *VERTICE;
-VERTICE solucao[MAX_VERTICES]; // Array que irá guardar a solução do ciclo hamiltoniano
+VERTICE solucao[MAX_VERTICES]; // Array que irá guardar a solução do ciclo
+ // hamiltoniano
// Cria Vértice e retorna
-VERTICE criaVertice(char id){
- VERTICE novoVertice = (VERTICE) malloc( sizeof(NO) ); // Aloca um novo Vértice
- novoVertice->id = id;
- novoVertice->nroVizinhos = 0;
- novoVertice->visitado = false;
- for (int i = 0; i < MAX_ARESTAS; i++){
- novoVertice->vizinhos[i] = NULL;
- }
- return novoVertice;
+VERTICE criaVertice(char id) {
+ VERTICE novoVertice = (VERTICE)malloc(sizeof(NO)); // Aloca um novo Vértice
+ novoVertice->id = id;
+ novoVertice->nroVizinhos = 0;
+ novoVertice->visitado = false;
+ for (int i = 0; i < MAX_ARESTAS; i++) {
+ novoVertice->vizinhos[i] = NULL;
+ }
+ return novoVertice;
}
// Liga os vértices passados como parâmetro
-bool ligaVertices(VERTICE v1, VERTICE v2){
- int aux = 0;
- while(v1->vizinhos[aux] != NULL){ // Busca a primeira posição 'vazia'(NULL) dos vizinhos
- aux++;
- }
- v1->vizinhos[aux] = v2; // Adiciona o novo vizinho a lista de vizinhos
- aux = 0;
- while(v2->vizinhos[aux] != NULL){ // Busca a primeira posição 'vazia'(NULL) dos vizinhos
- aux++;
- }
- v2->vizinhos[aux] = v1; // Adiciona o novo vizinho a lista de vizinhos
- v1->nroVizinhos++; // Incrementa o número de vizinhos
- v2->nroVizinhos++; // Incrementa o número de vizinhos
+bool ligaVertices(VERTICE v1, VERTICE v2) {
+ int aux = 0;
+ while (v1->vizinhos[aux] !=
+ NULL) { // Busca a primeira posição 'vazia'(NULL) dos vizinhos
+ aux++;
+ }
+ v1->vizinhos[aux] = v2; // Adiciona o novo vizinho a lista de vizinhos
+ aux = 0;
+ while (v2->vizinhos[aux] !=
+ NULL) { // Busca a primeira posição 'vazia'(NULL) dos vizinhos
+ aux++;
+ }
+ v2->vizinhos[aux] = v1; // Adiciona o novo vizinho a lista de vizinhos
+ v1->nroVizinhos++; // Incrementa o número de vizinhos
+ v2->nroVizinhos++; // Incrementa o número de vizinhos
}
-bool cicloHamiltonianoAuxiliar(int aux){
-
- if( aux == MAX_VERTICES ){
- for (int i = 0; i < solucao[aux-1]->nroVizinhos; i++){
- if( solucao[aux-1]->vizinhos[i] == solucao[0] ){
- return true;
- }
- }
- return false;
- }
-
- VERTICE s = solucao[aux-1]; // Auxiliar para simplificar o código
-
- for (int i = 0; i < s->nroVizinhos; i++){ // Percorre todos os vizinhos do vértice de posição aux-1 no array solução
- if( s->vizinhos[i]->visitado == false ){
- s->vizinhos[i]->visitado = true;
- solucao[aux] = s->vizinhos[i];
- if( cicloHamiltonianoAuxiliar(aux+1) == true ){
- return true;
- }
- s->vizinhos[i]->visitado = false;
- }
- }
-
- return false;
+bool cicloHamiltonianoAuxiliar(int aux) {
+
+ if (aux == MAX_VERTICES) {
+ for (int i = 0; i < solucao[aux - 1]->nroVizinhos; i++) {
+ if (solucao[aux - 1]->vizinhos[i] == solucao[0]) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ VERTICE s = solucao[aux - 1]; // Auxiliar para simplificar o código
+
+ for (int i = 0; i < s->nroVizinhos;
+ i++) { // Percorre todos os vizinhos do vértice de posição aux-1 no array
+ // solução
+ if (s->vizinhos[i]->visitado == false) {
+ s->vizinhos[i]->visitado = true;
+ solucao[aux] = s->vizinhos[i];
+ if (cicloHamiltonianoAuxiliar(aux + 1) == true) {
+ return true;
+ }
+ s->vizinhos[i]->visitado = false;
+ }
+ }
+
+ return false;
}
-bool cicloHamiltoniano(VERTICE grafo[MAX_VERTICES]){
- grafo[0]->visitado = true; // Marca a posição inicial como visitada
- solucao[0] = grafo[0]; // Array que irá guardar a solução do ciclo
- return cicloHamiltonianoAuxiliar(1);
+bool cicloHamiltoniano(VERTICE grafo[MAX_VERTICES]) {
+ grafo[0]->visitado = true; // Marca a posição inicial como visitada
+ solucao[0] = grafo[0]; // Array que irá guardar a solução do ciclo
+ return cicloHamiltonianoAuxiliar(1);
}
-int main(){
-
- // Grafo conjunto de vértices em um array
- VERTICE GRAFO[MAX_VERTICES];
- GRAFO[0] = criaVertice('A');
- GRAFO[1] = criaVertice('B');
- GRAFO[2] = criaVertice('C');
- GRAFO[3] = criaVertice('D');
- GRAFO[4] = criaVertice('E');
- GRAFO[5] = criaVertice('F');
-
- // Liga todos os vértices de acordo com o GRAFO apresentado na introdução
- ligaVertices(GRAFO[0], GRAFO[1]); // A - B
- ligaVertices(GRAFO[0], GRAFO[2]); // A - C
- ligaVertices(GRAFO[1], GRAFO[3]); // B - D
- ligaVertices(GRAFO[2], GRAFO[3]); // D - C
- ligaVertices(GRAFO[1], GRAFO[4]); // B - E
- ligaVertices(GRAFO[3], GRAFO[4]); // D - E
- ligaVertices(GRAFO[4], GRAFO[5]); // E - F
- ligaVertices(GRAFO[3], GRAFO[5]); // D - F
- ligaVertices(GRAFO[1], GRAFO[5]); // B - F
-
- for (int i = 0; i < MAX_VERTICES; i++){
- solucao[i] = criaVertice('0');
- }
-
- if( cicloHamiltoniano(GRAFO) ){
- printf("Ciclo Hamiltoniano:\n");
- for (int i = 0; i < MAX_VERTICES; i++){
- printf("%c, ",solucao[i]->id);
- }
- printf("\n\n");
- }else{
- printf("Nao possui Ciclo Hamiltoniano\n");
- }
-
- return 0;
+int main() {
+
+ // Grafo conjunto de vértices em um array
+ VERTICE GRAFO[MAX_VERTICES];
+ GRAFO[0] = criaVertice('A');
+ GRAFO[1] = criaVertice('B');
+ GRAFO[2] = criaVertice('C');
+ GRAFO[3] = criaVertice('D');
+ GRAFO[4] = criaVertice('E');
+ GRAFO[5] = criaVertice('F');
+
+ // Liga todos os vértices de acordo com o GRAFO apresentado na introdução
+ ligaVertices(GRAFO[0], GRAFO[1]); // A - B
+ ligaVertices(GRAFO[0], GRAFO[2]); // A - C
+ ligaVertices(GRAFO[1], GRAFO[3]); // B - D
+ ligaVertices(GRAFO[2], GRAFO[3]); // D - C
+ ligaVertices(GRAFO[1], GRAFO[4]); // B - E
+ ligaVertices(GRAFO[3], GRAFO[4]); // D - E
+ ligaVertices(GRAFO[4], GRAFO[5]); // E - F
+ ligaVertices(GRAFO[3], GRAFO[5]); // D - F
+ ligaVertices(GRAFO[1], GRAFO[5]); // B - F
+
+ for (int i = 0; i < MAX_VERTICES; i++) {
+ solucao[i] = criaVertice('0');
+ }
+
+ if (cicloHamiltoniano(GRAFO)) {
+ printf("Ciclo Hamiltoniano:\n");
+ for (int i = 0; i < MAX_VERTICES; i++) {
+ printf("%c, ", solucao[i]->id);
+ }
+ printf("\n\n");
+ } else {
+ printf("Nao possui Ciclo Hamiltoniano\n");
+ }
+
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/Heapsort.c b/src/c/Heapsort.c
index ca6e1699..4437c6e9 100644
--- a/src/c/Heapsort.c
+++ b/src/c/Heapsort.c
@@ -1,66 +1,61 @@
#include
-void heapify(int arr[], int n, int i)
-{
- int largest = i;
- int left = 2 * i + 1;
- int right = 2 * i + 2;
-
- if (left < n && arr[left] > arr[largest])
- largest = left;
-
- // If the right child is larger than the largest so far
- if (right < n && arr[right] > arr[largest])
- largest = right;
-
- // If the largest element is not the root
- if (largest != i)
- {
- // Swap the largest element with the root
- int temp = arr[i];
- arr[i] = arr[largest];
- arr[largest] = temp;
-
- // Recursively heapify the affected sub-tree
- heapify(arr, n, largest);
- }
+void heapify(int arr[], int n, int i) {
+ int largest = i;
+ int left = 2 * i + 1;
+ int right = 2 * i + 2;
+
+ if (left < n && arr[left] > arr[largest])
+ largest = left;
+
+ // If the right child is larger than the largest so far
+ if (right < n && arr[right] > arr[largest])
+ largest = right;
+
+ // If the largest element is not the root
+ if (largest != i) {
+ // Swap the largest element with the root
+ int temp = arr[i];
+ arr[i] = arr[largest];
+ arr[largest] = temp;
+
+ // Recursively heapify the affected sub-tree
+ heapify(arr, n, largest);
+ }
}
-void heapsort(int arr[], int n)
-{
- // Build a max heap
- int i;
- for (i = n / 2 - 1; i >= 0; i--)
- heapify(arr, n, i);
-
- // One by one extract elements from the heap
- for (i = n - 1; i > 0; i--)
- {
- // Move the current root to the end
- int temp = arr[0];
- arr[0] = arr[i];
- arr[i] = temp;
-
- // Call max heapify on the reduced heap
- heapify(arr, i, 0);
- }
+void heapsort(int arr[], int n) {
+ // Build a max heap
+ int i;
+ for (i = n / 2 - 1; i >= 0; i--)
+ heapify(arr, n, i);
+
+ // One by one extract elements from the heap
+ for (i = n - 1; i > 0; i--) {
+ // Move the current root to the end
+ int temp = arr[0];
+ arr[0] = arr[i];
+ arr[i] = temp;
+
+ // Call max heapify on the reduced heap
+ heapify(arr, i, 0);
+ }
}
-int main()
-{
- int arr[] = {12, 21, 13, 5, 1, 7};
- int i;
- int n = sizeof(arr) / sizeof(arr[0]);
+int main() {
+ int arr[] = {12, 21, 13, 5, 1, 7};
+ int i;
+ int n = sizeof(arr) / sizeof(arr[0]);
- printf("Original array: ");
- for (i = 0; i < n; i++)
- printf("%d ", arr[i]);
+ printf("Original array: ");
+ for (i = 0; i < n; i++)
+ printf("%d ", arr[i]);
- heapsort(arr, n);
+ heapsort(arr, n);
- printf("\nSorted array: ");
- for (i = 0; i < n; i++)
- printf("%d ", arr[i]);
+ printf("\nSorted array: ");
+ for (i = 0; i < n; i++)
+ printf("%d ", arr[i]);
- return 0;
+ return 0;
}
diff --git a/src/c/InsertionSort.c b/src/c/InsertionSort.c
index 69c9b8fb..5605bd91 100644
--- a/src/c/InsertionSort.c
+++ b/src/c/InsertionSort.c
@@ -4,45 +4,48 @@ Algoritmo de ordenação Insertion Sort em C
#include // Necessário para usar input e output
#include // Necessário para usar a função rand()
-#include // Necessário para inicializar a semente de números aleatórios
+#include // Necessário para inicializar a semente de números aleatórios
-// Definimos a função insertion_sort que recebe como argumento o vetor a ser ordenado e seu tamanho n
+// Definimos a função insertion_sort que recebe como argumento o vetor a ser
+// ordenado e seu tamanho n
void insertion_sort(int arr[], int n) {
- int i, j, key;
- // Percorremos todos os elementos do vetor a partir do segundo elemento
- for (i = 1; i < n; i++) {
- // Armazenamos o valor do elemento atual em key
- key = arr[i];
- // Inicializamos o índice j como o elemento anterior ao elemento atual
- j = i - 1;
- // Enquanto j é maior ou igual a 0 e o elemento atual é menor do que o elemento na posição j do vetor,
- // movemos o elemento na posição j uma posição para a direita e decrementamos j
- while (j >= 0 && arr[j] > key) {
- arr[j + 1] = arr[j];
- j = j - 1;
- }
- // Quando o loop interno termina, colocamos o elemento atual em sua posição correta
- arr[j + 1] = key;
+ int i, j, key;
+ // Percorremos todos os elementos do vetor a partir do segundo elemento
+ for (i = 1; i < n; i++) {
+ // Armazenamos o valor do elemento atual em key
+ key = arr[i];
+ // Inicializamos o índice j como o elemento anterior ao elemento atual
+ j = i - 1;
+ // Enquanto j é maior ou igual a 0 e o elemento atual é menor do que o
+ // elemento na posição j do vetor, movemos o elemento na posição j uma
+ // posição para a direita e decrementamos j
+ while (j >= 0 && arr[j] > key) {
+ arr[j + 1] = arr[j];
+ j = j - 1;
}
+ // Quando o loop interno termina, colocamos o elemento atual em sua posição
+ // correta
+ arr[j + 1] = key;
+ }
}
// Função principal
int main() {
- int i, n, arr[100];
- srand(time(NULL)); // Inicializa a semente de números aleatórios
- printf("Entre com o numero de elementos no vetor: ");
- scanf("%d", &n);
- printf("Vetor de entrada:\n");
- for (i = 0; i < n; i++) {
- arr[i] = rand() % 100; // Gera um valor aleatório entre 0 e 99
- printf("%d ", arr[i]); // Imprime o valor gerado
- }
- printf("\n");
- insertion_sort(arr, n);
- printf("Vetor ordenado em ordem crescente:\n");
- for (i = 0; i < n; i++) {
- printf("%d ", arr[i]);
- }
- printf("\n");
- return 0;
+ int i, n, arr[100];
+ srand(time(NULL)); // Inicializa a semente de números aleatórios
+ printf("Entre com o numero de elementos no vetor: ");
+ scanf("%d", &n);
+ printf("Vetor de entrada:\n");
+ for (i = 0; i < n; i++) {
+ arr[i] = rand() % 100; // Gera um valor aleatório entre 0 e 99
+ printf("%d ", arr[i]); // Imprime o valor gerado
+ }
+ printf("\n");
+ insertion_sort(arr, n);
+ printf("Vetor ordenado em ordem crescente:\n");
+ for (i = 0; i < n; i++) {
+ printf("%d ", arr[i]);
+ }
+ printf("\n");
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/LinearSearch.c b/src/c/LinearSearch.c
index bf28b592..39e5c991 100644
--- a/src/c/LinearSearch.c
+++ b/src/c/LinearSearch.c
@@ -1,21 +1,18 @@
#include
int buscaSequencial(int vetor[], int size, int buscado) {
- for (int i = 0; i < size; i++)
- {
- if (vetor[i] == buscado)
- {
- return i;
- }
+ for (int i = 0; i < size; i++) {
+ if (vetor[i] == buscado) {
+ return i;
}
- return -1;
+ }
+ return -1;
}
-int main(){
+int main() {
- int a[] = {1, 2, 3, 4, 5, 6, 7, 8};
- int n = sizeof(a) / sizeof(a[0]);
- printf("Valor %d no índice %d\n", 3, buscaSequencial(a, n, 3));
- printf("Valor %d no índice %d\n", 9, buscaSequencial(a, n, 9));
+ int a[] = {1, 2, 3, 4, 5, 6, 7, 8};
+ int n = sizeof(a) / sizeof(a[0]);
+ printf("Valor %d no índice %d\n", 3, buscaSequencial(a, n, 3));
+ printf("Valor %d no índice %d\n", 9, buscaSequencial(a, n, 9));
}
-
diff --git a/src/c/LinearSearchRecursive.c b/src/c/LinearSearchRecursive.c
index ef5159a3..ffdb2001 100644
--- a/src/c/LinearSearchRecursive.c
+++ b/src/c/LinearSearchRecursive.c
@@ -1,25 +1,22 @@
#include
int buscaSequencialRecursiva(int vetor[], int i, int buscado, int size) {
-
- if (i == size)
- {
- return -1;
- }
- else if (vetor[i] == buscado)
- {
- return i;
- }
- else
- {
- return buscaSequencialRecursiva(vetor, i+1, buscado, size);
- }
+
+ if (i == size) {
+ return -1;
+ } else if (vetor[i] == buscado) {
+ return i;
+ } else {
+ return buscaSequencialRecursiva(vetor, i + 1, buscado, size);
+ }
}
-int main(){
+int main() {
- int vetor[] = {1, 2, 3, 4, 5, 6, 7, 8};
- size_t n = sizeof(vetor) / sizeof(vetor[0]);
- printf("Valor %d no índice %d\n", 1, buscaSequencialRecursiva(vetor, 0, 1, n));
- printf("Valor %d no índice %d\n", 10, buscaSequencialRecursiva(vetor, 0, 10, n));
+ int vetor[] = {1, 2, 3, 4, 5, 6, 7, 8};
+ size_t n = sizeof(vetor) / sizeof(vetor[0]);
+ printf("Valor %d no índice %d\n", 1,
+ buscaSequencialRecursiva(vetor, 0, 1, n));
+ printf("Valor %d no índice %d\n", 10,
+ buscaSequencialRecursiva(vetor, 0, 10, n));
}
diff --git a/src/c/LinearSearchSentinel.c b/src/c/LinearSearchSentinel.c
index 67f32822..37071d8b 100644
--- a/src/c/LinearSearchSentinel.c
+++ b/src/c/LinearSearchSentinel.c
@@ -1,7 +1,8 @@
/*
-* Exemplo de Busca Sentinela em C
-* Objetivo: Encontrar um valor em um vetor sem precisar testar todos os valores dentro do laço
-*/
+ * Exemplo de Busca Sentinela em C
+ * Objetivo: Encontrar um valor em um vetor sem precisar testar todos os
+ *valores dentro do laço
+ */
#include
#include
@@ -9,35 +10,41 @@
#define TAM_VETOR 10
-// Busca sentinela, realiza uma busca sequencial sem precisar testar a chave a cada passo do laço de busca
-int buscaSentinela(int vetor[], int chave){
- vetor[TAM_VETOR] = chave; // Coloca o valor buscado (chave) na última posição do vetor
- int aux = 0; // Variável de controle do laço
- while( vetor[aux] != chave ) // Enquanto não encontrar o valor (chave) incrementa 1 em aux
- aux++;
- 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
- return -1; // Não encontrou
- else // Caso aux seja diferente, significa que encontrou o valor e quebrou o laço, o aux é a posição do valor buscado
- return aux; // Encontrou
+// Busca sentinela, realiza uma busca sequencial sem precisar testar a chave a
+// cada passo do laço de busca
+int buscaSentinela(int vetor[], int chave) {
+ vetor[TAM_VETOR] =
+ chave; // Coloca o valor buscado (chave) na última posição do vetor
+ int aux = 0; // Variável de controle do laço
+ while (vetor[aux] !=
+ chave) // Enquanto não encontrar o valor (chave) incrementa 1 em aux
+ aux++;
+ 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
+ return -1; // Não encontrou
+ else // Caso aux seja diferente, significa que encontrou o valor e quebrou o
+ // laço, o aux é a posição do valor buscado
+ return aux; // Encontrou
}
-int main(){
+int main() {
- int vetor[TAM_VETOR+1]; // Declara o vetor com +1 pois é a posição que será utilizada pela sentinela
+ int vetor[TAM_VETOR + 1]; // Declara o vetor com +1 pois é a posição que será
+ // utilizada pela sentinela
- // Preenche o vetor com valores aleatórios 0-1000
- srand(time(NULL));
- for(int i = 0; i < TAM_VETOR; i++){
- vetor[i] = rand()%1000;
- printf("%d, ", vetor[i]);
- }
+ // Preenche o vetor com valores aleatórios 0-1000
+ srand(time(NULL));
+ for (int i = 0; i < TAM_VETOR; i++) {
+ vetor[i] = rand() % 1000;
+ printf("%d, ", vetor[i]);
+ }
- // Faz a busca, passando como parâmetro o vetor e a chave que deseja buscar
- int res = buscaSentinela(vetor, vetor[TAM_VETOR-2]);
- if( res != -1 )
- printf("\n\nValor %d encontrado na posicao %d.\n\n", vetor[res], res);
- else
- printf("\n\nValor não encontrado no vetor\n\n");
+ // Faz a busca, passando como parâmetro o vetor e a chave que deseja buscar
+ int res = buscaSentinela(vetor, vetor[TAM_VETOR - 2]);
+ if (res != -1)
+ printf("\n\nValor %d encontrado na posicao %d.\n\n", vetor[res], res);
+ else
+ printf("\n\nValor não encontrado no vetor\n\n");
- return 0;
+ return 0;
}
diff --git a/src/c/MaxRecursive.c b/src/c/MaxRecursive.c
index 9c9ac09e..b173c575 100644
--- a/src/c/MaxRecursive.c
+++ b/src/c/MaxRecursive.c
@@ -1,7 +1,7 @@
/*
-* Exemplos de funções para achar maior número de um vetor
-* As 3 são recursivas porém apenas a MaxDC utiliza divisão e conquista
-*/
+ * Exemplos de funções para achar maior número de um vetor
+ * As 3 são recursivas porém apenas a MaxDC utiliza divisão e conquista
+ */
#include
#include
@@ -9,81 +9,62 @@
#define MAX 10
// Maximo usando Divisão e Conquista
-int MaxDC(int *vetor, int inicio, int fim)
-{
- int aux1, aux2;
- int meio = ( inicio + fim ) / 2;
+int MaxDC(int *vetor, int inicio, int fim) {
+ int aux1, aux2;
+ int meio = (inicio + fim) / 2;
- if( inicio == fim )
- {
- return vetor[inicio];
- }
+ if (inicio == fim) {
+ return vetor[inicio];
+ }
- aux1 = MaxDC(vetor, inicio, meio);
- aux2 = MaxDC(vetor, meio+1, fim);
+ aux1 = MaxDC(vetor, inicio, meio);
+ aux2 = MaxDC(vetor, meio + 1, fim);
- if( aux1 > aux2 )
- {
- return aux1;
- }
- else
- {
- return aux2;
- }
+ if (aux1 > aux2) {
+ return aux1;
+ } else {
+ return aux2;
+ }
}
-void max1(int *vetor, int maximo, int indice)
-{
- if( vetor[indice] > maximo )
- {
- maximo = vetor[indice];
- }
+void max1(int *vetor, int maximo, int indice) {
+ if (vetor[indice] > maximo) {
+ maximo = vetor[indice];
+ }
- if( indice < MAX-1 )
- {
- max1(vetor, maximo, indice+1);
- }
- else
- {
- printf("\n\nMax1: %d\n",maximo);
- }
+ if (indice < MAX - 1) {
+ max1(vetor, maximo, indice + 1);
+ } else {
+ printf("\n\nMax1: %d\n", maximo);
+ }
}
-int max2(int vetor[], int tamVetor)
-{
- if (tamVetor == 1)
- {
- return vetor[0]; // só tem 1 elemento
- }
- else
- {
- int x = max2(vetor, tamVetor-1);
+int max2(int vetor[], int tamVetor) {
+ if (tamVetor == 1) {
+ return vetor[0]; // só tem 1 elemento
+ } else {
+ int x = max2(vetor, tamVetor - 1);
- if (x > vetor[tamVetor-1])
- {
- return x;
- }
- else
- {
- return vetor[tamVetor-1];
- }
+ if (x > vetor[tamVetor - 1]) {
+ return x;
+ } else {
+ return vetor[tamVetor - 1];
}
+ }
}
-int main()
-{
- int vetor[MAX];
+int main() {
+ int vetor[MAX];
- for (int i = 0; i < MAX; ++i)
- {
- vetor[i] = (rand() % 90) + 10; // 10 a 99
- printf("%d, ", vetor[i]);
- }
+ for (int i = 0; i < MAX; ++i) {
+ vetor[i] = (rand() % 90) + 10; // 10 a 99
+ printf("%d, ", vetor[i]);
+ }
- max1(vetor, vetor[0], 1);
+ max1(vetor, vetor[0], 1);
- printf("\nMax2: %d\n", max2(vetor, MAX) );
- printf("\nMaxDC: %d\n\n", MaxDC(vetor, 0, MAX-1) );
+ printf("\nMax2: %d\n", max2(vetor, MAX));
+ printf("\nMaxDC: %d\n\n", MaxDC(vetor, 0, MAX - 1));
- return 0;
+ return 0;
}
diff --git a/src/c/MergeSort.c b/src/c/MergeSort.c
index f536e462..f3470e26 100644
--- a/src/c/MergeSort.c
+++ b/src/c/MergeSort.c
@@ -1,13 +1,13 @@
/*
-* Exemplo de Ordenação utilizando Merge Sort
-*
-* Dividir para conquistar:
-*
-* Dividir: Dividir os dados em subsequências pequenas;
-* Conquistar: Classificar as duas metades recursivamente aplicando o merge sort;
-* Combinar: Juntar as duas metades em um único conjunto já classificado.
-*
-*/
+ * Exemplo de Ordenação utilizando Merge Sort
+ *
+ * Dividir para conquistar:
+ *
+ * Dividir: Dividir os dados em subsequências pequenas;
+ * Conquistar: Classificar as duas metades recursivamente aplicando o merge
+ *sort; Combinar: Juntar as duas metades em um único conjunto já classificado.
+ *
+ */
#include
#include
@@ -20,54 +20,53 @@ void merge(int vetor[], int tamanho) {
int i = 0, j = meio, k = 0;
int aux[tamanho];
- while( i < meio && j < tamanho ){
- if( vetor[i] <= vetor[j] )
+ while (i < meio && j < tamanho) {
+ if (vetor[i] <= vetor[j])
aux[k] = vetor[i++];
else
aux[k] = vetor[j++];
k++;
}
-
- if( i == meio )
- while( j < tamanho )
+
+ if (i == meio)
+ while (j < tamanho)
aux[k++] = vetor[j++];
else
- while( i < meio )
+ while (i < meio)
aux[k++] = vetor[i++];
-
- for( i = 0; i < tamanho; i++ )
+
+ for (i = 0; i < tamanho; i++)
vetor[i] = aux[i];
}
-
-int mergeSort(int vetor[], int tamanho){
- int meio = tamanho / 2;
- if( tamanho > 1 ){
- mergeSort(vetor, meio);
- mergeSort(vetor + meio, tamanho - meio);
- merge(vetor, tamanho);
- }
+int mergeSort(int vetor[], int tamanho) {
+ int meio = tamanho / 2;
+ if (tamanho > 1) {
+ mergeSort(vetor, meio);
+ mergeSort(vetor + meio, tamanho - meio);
+ merge(vetor, tamanho);
+ }
}
-int main(){
+int main() {
+
+ int vetor[TAM_VETOR];
- int vetor[TAM_VETOR];
-
- // Preenche o vetor com valores aleatórios 0-1000
- srand(time(NULL));
- for(int i = 0; i < TAM_VETOR; i++){
- vetor[i] = rand()%1000;
- printf("%d, ", vetor[i]);
- }
-
- printf("\n\n");
-
- mergeSort(vetor, TAM_VETOR);
+ // Preenche o vetor com valores aleatórios 0-1000
+ srand(time(NULL));
+ for (int i = 0; i < TAM_VETOR; i++) {
+ vetor[i] = rand() % 1000;
+ printf("%d, ", vetor[i]);
+ }
+
+ printf("\n\n");
+
+ mergeSort(vetor, TAM_VETOR);
+
+ for (int i = 0; i < TAM_VETOR; i++) {
+ printf("%d, ", vetor[i]);
+ }
- for(int i = 0; i < TAM_VETOR; i++){
- printf("%d, ", vetor[i]);
- }
-
- return 0;
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/MinMaxDC.c b/src/c/MinMaxDC.c
index b45f0205..aac43e07 100644
--- a/src/c/MinMaxDC.c
+++ b/src/c/MinMaxDC.c
@@ -10,48 +10,48 @@
* @param max Pointer to store the maximum element
*/
-void MinAndMax(int arr[], int left, int right, int* min, int* max) {
- // if there is only one element in the sub-array, set it as both min and max
- if (left == right) {
- *min = *max = arr[left];
- return;
+void MinAndMax(int arr[], int left, int right, int *min, int *max) {
+ // if there is only one element in the sub-array, set it as both min and max
+ if (left == right) {
+ *min = *max = arr[left];
+ return;
+ }
+
+ // if there are two elements in the sub-array, compare and set min and max
+ if (right - left == 1) {
+ if (arr[left] < arr[right]) {
+ *min = arr[left];
+ *max = arr[right];
+ } else {
+ *min = arr[right];
+ *max = arr[left];
}
+ return;
+ }
- // if there are two elements in the sub-array, compare and set min and max
- if (right - left == 1) {
- if (arr[left] < arr[right]) {
- *min = arr[left];
- *max = arr[right];
- } else {
- *min = arr[right];
- *max = arr[left];
- }
- return;
- }
-
- // calculate the middle index of the sub-array
- int mid = (left + right) / 2;
- int leftMin, leftMax, rightMin, rightMax;
+ // calculate the middle index of the sub-array
+ int mid = (left + right) / 2;
+ int leftMin, leftMax, rightMin, rightMax;
- // recursively find min and max in the left and right sub-arrays
- MinAndMax(arr, left, mid, &leftMin, &leftMax);
- MinAndMax(arr, mid + 1, right, &rightMin, &rightMax);
+ // recursively find min and max in the left and right sub-arrays
+ MinAndMax(arr, left, mid, &leftMin, &leftMax);
+ MinAndMax(arr, mid + 1, right, &rightMin, &rightMax);
- // update the minimum and maximum values
- *min = (leftMin < rightMin) ? leftMin : rightMin;
- *max = (leftMax > rightMax) ? leftMax : rightMax;
+ // update the minimum and maximum values
+ *min = (leftMin < rightMin) ? leftMin : rightMin;
+ *max = (leftMax > rightMax) ? leftMax : rightMax;
}
int main() {
- int arr[] = {10, 5, 20, 8, 15, 30, -12, 24};
- int arrSize = sizeof(arr) / sizeof(arr[0]);
+ int arr[] = {10, 5, 20, 8, 15, 30, -12, 24};
+ int arrSize = sizeof(arr) / sizeof(arr[0]);
- int min, max;
+ int min, max;
- MinAndMax(arr, 0, arrSize - 1, &min, &max);
+ MinAndMax(arr, 0, arrSize - 1, &min, &max);
- printf("Minimum element: %d\n", min);
- printf("Maximum element: %d\n", max);
+ printf("Minimum element: %d\n", min);
+ printf("Maximum element: %d\n", max);
- return 0;
+ return 0;
}
diff --git a/src/c/MinMaxIterative.c b/src/c/MinMaxIterative.c
index 87fda2c0..0ae3e0b9 100644
--- a/src/c/MinMaxIterative.c
+++ b/src/c/MinMaxIterative.c
@@ -1,23 +1,23 @@
#include
int main() {
- int array[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };
+ int array[8] = {1, 2, 3, 4, 5, 6, 7, 8};
- int min = array[0];
- int max = array[0];
+ int min = array[0];
+ int max = array[0];
- size_t length = sizeof(array) / sizeof(array[0]);
+ size_t length = sizeof(array) / sizeof(array[0]);
- for (int i = 1; i < length; ++i) {
- if (array[i] < min) {
- min = array[i];
- }
- if (array[i] > max) {
- max = array[i];
- }
+ for (int i = 1; i < length; ++i) {
+ if (array[i] < min) {
+ min = array[i];
}
+ if (array[i] > max) {
+ max = array[i];
+ }
+ }
- printf("min: %d\n", min);
- printf("max: %d\n", max);
- return 0;
+ printf("min: %d\n", min);
+ printf("max: %d\n", max);
+ return 0;
}
diff --git a/src/c/MinMaxRecursive.c b/src/c/MinMaxRecursive.c
index fcb64997..dcbdb235 100644
--- a/src/c/MinMaxRecursive.c
+++ b/src/c/MinMaxRecursive.c
@@ -1,25 +1,26 @@
/*
-* Exemplo de algoritmo recursivo.
-* Objetivo: encontrar o valor máximo e mínimo em um vetor, utilizando recursividade
-*/
+ * Exemplo de algoritmo recursivo.
+ * Objetivo: encontrar o valor máximo e mínimo em um vetor, utilizando
+ *recursividade
+ */
#include
#define TAM 10
-void MaxMin(int vetor[], int min, int max, int indice){
- if( vetor[indice] < min )
- min = vetor[indice];
- if( vetor[indice] > max )
- max = vetor[indice];
- if( indice < TAM-1 )
- MaxMin(vetor, min, max, indice+1);
- else
- printf("Min: %d \nMax: %d\n\n", min, max);
+void MaxMin(int vetor[], int min, int max, int indice) {
+ if (vetor[indice] < min)
+ min = vetor[indice];
+ if (vetor[indice] > max)
+ max = vetor[indice];
+ if (indice < TAM - 1)
+ MaxMin(vetor, min, max, indice + 1);
+ else
+ printf("Min: %d \nMax: %d\n\n", min, max);
}
-int main(){
- int vetor[TAM] = {9,2,1,8,6,3,4,5,0,7};
- MaxMin(vetor, vetor[0], vetor[0], 0);
- return 0;
+int main() {
+ int vetor[TAM] = {9, 2, 1, 8, 6, 3, 4, 5, 0, 7};
+ MaxMin(vetor, vetor[0], vetor[0], 0);
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/Palindrome.c b/src/c/Palindrome.c
index 6698f6dd..cdc59d0f 100644
--- a/src/c/Palindrome.c
+++ b/src/c/Palindrome.c
@@ -8,7 +8,7 @@ void calc_reverse(char *input, char *output) {
char *last_char = input + len_input - 1;
- for (int i=0; i < len_input; i++) {
+ for (int i = 0; i < len_input; i++) {
output[i] = *(last_char - i);
}
output[len_input] = '\0';
@@ -21,7 +21,7 @@ int main() {
printf("Digite uma palavra: ");
fgets(input, MAX_SIZE_WORD, stdin);
- //remove New Line from the end
+ // remove New Line from the end
input[strlen(input) - 1] = '\0';
calc_reverse(input, reverse);
diff --git a/src/c/Queue.c b/src/c/Queue.c
index 75efce52..35ad7a8c 100644
--- a/src/c/Queue.c
+++ b/src/c/Queue.c
@@ -1,6 +1,6 @@
/*
-* Exemplo de implementação de Fila em C
-*/
+ * Exemplo de implementação de Fila em C
+ */
#include
@@ -9,72 +9,74 @@
typedef int TIPOCHAVE;
-typedef struct{
- TIPOCHAVE chave;
-}REGISTRO;
+typedef struct {
+ TIPOCHAVE chave;
+} REGISTRO;
-typedef struct{
- REGISTRO A[MAX+1];
- int nroRegistros;
-}FILA;
+typedef struct {
+ REGISTRO A[MAX + 1];
+ int nroRegistros;
+} FILA;
-void inicializa(FILA* F){
- int i = 0;
- for (i; i < MAX-2; i++){
- F->A[i].chave = i*2;
- }
- F->nroRegistros = i;
+void inicializa(FILA *F) {
+ int i = 0;
+ for (i; i < MAX - 2; i++) {
+ F->A[i].chave = i * 2;
+ }
+ F->nroRegistros = i;
}
-void mostraFila(FILA* F){
- int i = 0;
- printf("FILA:\n");
- for (i; i < F->nroRegistros; i++){
- printf("[ %d ] ", F->A[i].chave);
- }
- printf("\n\n");
+void mostraFila(FILA *F) {
+ int i = 0;
+ printf("FILA:\n");
+ for (i; i < F->nroRegistros; i++) {
+ printf("[ %d ] ", F->A[i].chave);
+ }
+ printf("\n\n");
}
-bool insereFila(TIPOCHAVE ch, FILA* F){
- if( F->nroRegistros >= MAX )
- return false;
- F->A[F->nroRegistros].chave = ch;
- F->nroRegistros++;
- return true;
+bool insereFila(TIPOCHAVE ch, FILA *F) {
+ if (F->nroRegistros >= MAX)
+ return false;
+ F->A[F->nroRegistros].chave = ch;
+ F->nroRegistros++;
+ return true;
}
-bool removeFila(FILA* F){
- if( F->nroRegistros <= 0 )
- return false;
- int i = 1;
- for (i; i < F->nroRegistros; i++){
- F->A[i-1].chave = F->A[i].chave;
- }
- F->nroRegistros--;
- return true;
+bool removeFila(FILA *F) {
+ if (F->nroRegistros <= 0)
+ return false;
+ int i = 1;
+ for (i; i < F->nroRegistros; i++) {
+ F->A[i - 1].chave = F->A[i].chave;
+ }
+ F->nroRegistros--;
+ return true;
}
-int buscaFila(TIPOCHAVE ch, FILA* F){
- F->A[F->nroRegistros].chave = ch; // Coloca a ch na ultima posição para fazer busca Sentinela
- int i = 0;
- while( F->A[i].chave != ch )
- i++;
- if( i >= F->nroRegistros )
- return ERRO;
- return i;
+int buscaFila(TIPOCHAVE ch, FILA *F) {
+ F->A[F->nroRegistros].chave =
+ ch; // Coloca a ch na ultima posição para fazer busca Sentinela
+ int i = 0;
+ while (F->A[i].chave != ch)
+ i++;
+ if (i >= F->nroRegistros)
+ return ERRO;
+ return i;
}
-int main(){
- FILA fi;
- inicializa(&fi);
- mostraFila(&fi);
+int main() {
+ FILA fi;
+ inicializa(&fi);
+ mostraFila(&fi);
- insereFila(15, &fi);
- mostraFila(&fi);
+ insereFila(15, &fi);
+ mostraFila(&fi);
- removeFila(&fi);
- mostraFila(&fi);
+ removeFila(&fi);
+ mostraFila(&fi);
- printf("A chave buscada se encontra na posicao %d da fila\n\n", buscaFila(8, &fi) );
- return 0;
+ printf("A chave buscada se encontra na posicao %d da fila\n\n",
+ buscaFila(8, &fi));
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/QuickSort.c b/src/c/QuickSort.c
index 98c49507..87fae0c9 100644
--- a/src/c/QuickSort.c
+++ b/src/c/QuickSort.c
@@ -1,87 +1,87 @@
-#include
#include
+#include
void print_array(int array[], int size) {
- printf("[ ");
- for (int index = 0; index < size; ++index) {
- printf("%d", array[index]);
- if (index < size - 1) {
- printf(", ");
- }
+ printf("[ ");
+ for (int index = 0; index < size; ++index) {
+ printf("%d", array[index]);
+ if (index < size - 1) {
+ printf(", ");
}
- printf(" ]\n");
+ }
+ printf(" ]\n");
}
void swap(int array[], int src_index, int dest_index) {
- int temp = array[src_index];
- array[src_index] = array[dest_index];
- array[dest_index] = temp;
+ int temp = array[src_index];
+ array[src_index] = array[dest_index];
+ array[dest_index] = temp;
}
int lomuto_partition(int array[], int low, int high) {
- int pivot = array[high];
- int index = low;
+ int pivot = array[high];
+ int index = low;
- for (int j = low; j < high; ++j) {
- if (array[j] < pivot) {
- swap(array, index, j);
- ++index;
- }
+ for (int j = low; j < high; ++j) {
+ if (array[j] < pivot) {
+ swap(array, index, j);
+ ++index;
}
- swap(array, index, high);
- return index;
+ }
+ swap(array, index, high);
+ return index;
}
void quicksort_lomuto(int array[], int low, int high) {
- if (low < high) {
- int pivot = lomuto_partition(array, low, high);
- quicksort_lomuto(array, low, pivot - 1);
- quicksort_lomuto(array, pivot + 1, high);
- }
+ if (low < high) {
+ int pivot = lomuto_partition(array, low, high);
+ quicksort_lomuto(array, low, pivot - 1);
+ quicksort_lomuto(array, pivot + 1, high);
+ }
}
int hoare_partition(int array[], int low, int high) {
- int pivot = array[low];
- int i = low - 1;
- int j = high + 1;
+ int pivot = array[low];
+ int i = low - 1;
+ int j = high + 1;
- while (true) {
- do {
- ++i;
- } while (array[i] < pivot);
+ while (true) {
+ do {
+ ++i;
+ } while (array[i] < pivot);
- do {
- --j;
- } while (array[j] > pivot);
+ do {
+ --j;
+ } while (array[j] > pivot);
- if (i >= j) {
- return j;
- }
- swap(array, i, j);
+ if (i >= j) {
+ return j;
}
+ swap(array, i, j);
+ }
}
void quicksort_hoare(int array[], int low, int high) {
- if (low < high) {
- int pivot = hoare_partition(array, low, high);
- quicksort_hoare(array, low, pivot);
- quicksort_hoare(array, pivot + 1, high);
- }
+ if (low < high) {
+ int pivot = hoare_partition(array, low, high);
+ quicksort_hoare(array, low, pivot);
+ quicksort_hoare(array, pivot + 1, high);
+ }
}
int main() {
- int example_lomuto[] = {5, 3, 1, 4, 2};
- int example_hoare[] = {5, 3, 1, 4, 2};
- int size = 5;
+ int example_lomuto[] = {5, 3, 1, 4, 2};
+ int example_hoare[] = {5, 3, 1, 4, 2};
+ int size = 5;
- printf("lomuto quicksort partition:\n");
- print_array(example_lomuto, size);
- quicksort_lomuto(example_lomuto, 0, size - 1);
- print_array(example_lomuto, size);
+ printf("lomuto quicksort partition:\n");
+ print_array(example_lomuto, size);
+ quicksort_lomuto(example_lomuto, 0, size - 1);
+ print_array(example_lomuto, size);
- printf("hoare quicksort partition:\n");
- print_array(example_hoare, size);
- quicksort_hoare(example_hoare, 0, size - 1);
- print_array(example_hoare, size);
- return 0;
+ printf("hoare quicksort partition:\n");
+ print_array(example_hoare, size);
+ quicksort_hoare(example_hoare, 0, size - 1);
+ print_array(example_hoare, size);
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/RadixSort.c b/src/c/RadixSort.c
index 2c63dc6b..b4382076 100644
--- a/src/c/RadixSort.c
+++ b/src/c/RadixSort.c
@@ -1,65 +1,54 @@
#include
-void print_array(int array[], int size)
-{
- printf("[ ");
- for (int i = 0; i < size; i++)
- {
- printf("%d ", array[i]);
- }
- printf("]\n");
+void print_array(int array[], int size) {
+ printf("[ ");
+ for (int i = 0; i < size; i++) {
+ printf("%d ", array[i]);
+ }
+ printf("]\n");
}
-int get_max(int array[], int size)
-{
- int max = array[0];
- for (int i = 1; i < size; i++)
- {
- if (array[i] > max)
- max = array[i];
- }
- return max;
+int get_max(int array[], int size) {
+ int max = array[0];
+ for (int i = 1; i < size; i++) {
+ if (array[i] > max)
+ max = array[i];
+ }
+ return max;
}
-void radix_sort(int array[], int size)
-{
- int i;
- int semi_sorted[size];
- int significant_digit = 1;
- int largest_number = get_max(array, size);
+void radix_sort(int array[], int size) {
+ int i;
+ int semi_sorted[size];
+ int significant_digit = 1;
+ int largest_number = get_max(array, size);
- while (largest_number / significant_digit > 0)
- {
- int bucket[10] = {0};
- for (i = 0; i < size; i++)
- {
- bucket[(array[i] / significant_digit) % 10]++;
- }
- for (i = 1; i < 10; i++)
- {
- bucket[i] += bucket[i - 1];
- }
- for (i = size - 1; i >= 0; i--)
- {
- semi_sorted[--bucket[(array[i] / significant_digit) % 10]] = array[i];
- }
- for (i = 0; i < size; i++)
- {
- array[i] = semi_sorted[i];
- }
- significant_digit *= 10;
- }
+ while (largest_number / significant_digit > 0) {
+ int bucket[10] = {0};
+ for (i = 0; i < size; i++) {
+ bucket[(array[i] / significant_digit) % 10]++;
+ }
+ for (i = 1; i < 10; i++) {
+ bucket[i] += bucket[i - 1];
+ }
+ for (i = size - 1; i >= 0; i--) {
+ semi_sorted[--bucket[(array[i] / significant_digit) % 10]] = array[i];
+ }
+ for (i = 0; i < size; i++) {
+ array[i] = semi_sorted[i];
+ }
+ significant_digit *= 10;
+ }
}
-int main()
-{
- int array[10] = {45, 75, 89, 12, 34, 9, 67, 23, 90, 11};
- printf("Unsorted Array\n");
- print_array(array, 10);
+int main() {
+ int array[10] = {45, 75, 89, 12, 34, 9, 67, 23, 90, 11};
+ printf("Unsorted Array\n");
+ print_array(array, 10);
- radix_sort(array, 10);
+ radix_sort(array, 10);
- printf("Sorted Array\n");
- print_array(array, 10);
- return 0;
+ printf("Sorted Array\n");
+ print_array(array, 10);
+ return 0;
}
diff --git a/src/c/SelectionSort.c b/src/c/SelectionSort.c
index 8fc38542..4cbee813 100644
--- a/src/c/SelectionSort.c
+++ b/src/c/SelectionSort.c
@@ -1,41 +1,35 @@
#include
-void swap(int array[], int i, int j)
-{
- int temp = array[i];
- array[i] = array[j];
- array[j] = temp;
+void swap(int array[], int i, int j) {
+ int temp = array[i];
+ array[i] = array[j];
+ array[j] = temp;
}
-void selection_sort(int array[], int n)
-{
- int min, i, j;
- for (i = 0; i < n; i++)
- {
- min = i;
- for (j = i + 1; j < n; j++)
- {
- if (array[min] > array[j])
- {
- min = j;
- }
- }
- if (min != i)
- swap(array, min, i);
+void selection_sort(int array[], int n) {
+ int min, i, j;
+ for (i = 0; i < n; i++) {
+ min = i;
+ for (j = i + 1; j < n; j++) {
+ if (array[min] > array[j]) {
+ min = j;
+ }
}
+ if (min != i)
+ swap(array, min, i);
+ }
}
-int main()
-{
- int array_size = 10;
- int array[10] = {45, 7, 125, 18, 3, 5, 11, 107, 60, 4};
+int main() {
+ int array_size = 10;
+ int array[10] = {45, 7, 125, 18, 3, 5, 11, 107, 60, 4};
- selection_sort(array, array_size);
+ selection_sort(array, array_size);
- printf("Sorted Array:\n");
- int i;
- for (i = 0; i < array_size; i++)
- printf("%d ", array[i]);
+ printf("Sorted Array:\n");
+ int i;
+ for (i = 0; i < array_size; i++)
+ printf("%d ", array[i]);
- return 0;
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/SinglyLinkedList.c b/src/c/SinglyLinkedList.c
index 9e5cad76..5411563c 100644
--- a/src/c/SinglyLinkedList.c
+++ b/src/c/SinglyLinkedList.c
@@ -1,272 +1,266 @@
-#include
#include
+#include
typedef struct tno {
- int dado;
- struct tno * anterior;
- struct tno * proximo;
+ int dado;
+ struct tno *anterior;
+ struct tno *proximo;
} tipoNo;
-typedef tipoNo * pnoh;
+typedef tipoNo *pnoh;
typedef struct {
- int tamanho;
- pnoh primeiro;
- pnoh ultimo;
+ int tamanho;
+ pnoh primeiro;
+ pnoh ultimo;
} tcabec;
-typedef tcabec * TLista;
+typedef tcabec *TLista;
TLista criaLista() {
- TLista c = (tcabec*) malloc(sizeof(tcabec));
+ TLista c = (tcabec *)malloc(sizeof(tcabec));
- c->tamanho = 0;
- c->primeiro = NULL;
- c->ultimo = NULL;
+ c->tamanho = 0;
+ c->primeiro = NULL;
+ c->ultimo = NULL;
- return c;
+ return c;
}
TLista appendLista(TLista lst, int dado) {
- pnoh novono = (tipoNo*) malloc(sizeof(tipoNo));
+ pnoh novono = (tipoNo *)malloc(sizeof(tipoNo));
- novono->dado = dado;
- novono->anterior = lst->ultimo;
- novono->proximo = NULL;
+ novono->dado = dado;
+ novono->anterior = lst->ultimo;
+ novono->proximo = NULL;
- if (lst->tamanho == 0) {
- lst->primeiro = novono;
- } else {
- lst->ultimo->proximo = novono;
- }
+ if (lst->tamanho == 0) {
+ lst->primeiro = novono;
+ } else {
+ lst->ultimo->proximo = novono;
+ }
- lst->ultimo = novono;
- lst->tamanho++;
+ lst->ultimo = novono;
+ lst->tamanho++;
- return lst;
+ return lst;
}
-int lenLista(TLista lst) {
- return lst->tamanho;
-}
+int lenLista(TLista lst) { return lst->tamanho; }
-int primLista(TLista lst) {
- return lst->primeiro->dado;
-}
+int primLista(TLista lst) { return lst->primeiro->dado; }
-int ultLista(TLista lst) {
- return lst->ultimo->dado;
-}
+int ultLista(TLista lst) { return lst->ultimo->dado; }
-TLista insertLista(TLista lst, int i, int dado)
-{
- int tam = lenLista(lst);
+TLista insertLista(TLista lst, int i, int dado) {
+ int tam = lenLista(lst);
- if ((i < 0) || (i > tam)) {
- return NULL;
- }
+ if ((i < 0) || (i > tam)) {
+ return NULL;
+ }
- if ((lenLista(lst) == 0) || (i == tam)) {
- appendLista(lst, dado);
+ if ((lenLista(lst) == 0) || (i == tam)) {
+ appendLista(lst, dado);
+ } else {
+ pnoh novono = (tipoNo *)malloc(sizeof(tipoNo));
+ novono->dado = dado;
+
+ if (i == 0) {
+ novono->proximo = lst->primeiro;
+ lst->primeiro = novono;
} else {
- pnoh novono = (tipoNo*) malloc(sizeof(tipoNo));
- novono->dado = dado;
-
- if (i == 0) {
- novono->proximo = lst->primeiro;
- lst->primeiro = novono;
- } else {
- pnoh aux = lst->primeiro;
- int pos = 0;
-
- while (pos != (i - 1))
- {
- aux = aux->proximo;
- pos++;
- }
- novono->proximo = aux->proximo;
- aux->proximo = novono;
- }
+ pnoh aux = lst->primeiro;
+ int pos = 0;
- lst->tamanho++;
+ while (pos != (i - 1)) {
+ aux = aux->proximo;
+ pos++;
+ }
+ novono->proximo = aux->proximo;
+ aux->proximo = novono;
}
- return lst;
+ lst->tamanho++;
+ }
+
+ return lst;
}
pnoh infoLista(TLista lst, int i) {
- int tam = lenLista(lst);
+ int tam = lenLista(lst);
- if ((tam == 0) || (i < 0) || (i > tam)) {
- return NULL;
- }
+ if ((tam == 0) || (i < 0) || (i > tam)) {
+ return NULL;
+ }
- if (i == 0) {
- return lst->primeiro;
- }
+ if (i == 0) {
+ return lst->primeiro;
+ }
- if (i == tam - 1) {
- return lst->ultimo;
- }
+ if (i == tam - 1) {
+ return lst->ultimo;
+ }
- pnoh aux = lst->primeiro;
- int pos = 0;
+ pnoh aux = lst->primeiro;
+ int pos = 0;
- while (pos != i) {
- aux = aux->proximo;
- pos++;
- }
+ while (pos != i) {
+ aux = aux->proximo;
+ pos++;
+ }
- return aux;
+ return aux;
}
void removeLista(TLista lst, int i) {
- int tam = lenLista(lst);
+ int tam = lenLista(lst);
- if ((i < 0) || (i > tam) || (tam == 0)) {
- printf("Erro: indice inexistente dentro da Lista.");
- return;
- }
+ if ((i < 0) || (i > tam) || (tam == 0)) {
+ printf("Erro: indice inexistente dentro da Lista.");
+ return;
+ }
- if (tam == 1) {
- pnoh aux = lst->primeiro;
- lst->primeiro = NULL;
- lst->ultimo = NULL;
- lst->tamanho--;
+ if (tam == 1) {
+ pnoh aux = lst->primeiro;
+ lst->primeiro = NULL;
+ lst->ultimo = NULL;
+ lst->tamanho--;
- free(aux);
- } else {
- if (i == 0) {
- pnoh aux = lst->primeiro;
- lst->primeiro = aux->proximo;
- lst->tamanho--;
+ free(aux);
+ } else {
+ if (i == 0) {
+ pnoh aux = lst->primeiro;
+ lst->primeiro = aux->proximo;
+ lst->tamanho--;
- free(aux);
- } else {
- if (i == tam - 1) {
- pnoh aux = lst->ultimo;
+ free(aux);
+ } else {
+ if (i == tam - 1) {
+ pnoh aux = lst->ultimo;
- pnoh penultimo = lst->primeiro;
- int pos = 0;
+ pnoh penultimo = lst->primeiro;
+ int pos = 0;
- while (pos != i - 1) {
- penultimo = penultimo->proximo;
- pos++;
- }
+ while (pos != i - 1) {
+ penultimo = penultimo->proximo;
+ pos++;
+ }
- penultimo->proximo = NULL;
- lst->ultimo = penultimo;
+ penultimo->proximo = NULL;
+ lst->ultimo = penultimo;
- lst->tamanho--;
+ lst->tamanho--;
- free(aux);
- } else {
- pnoh anterior = lst->primeiro;
- int pos = 0;
+ free(aux);
+ } else {
+ pnoh anterior = lst->primeiro;
+ int pos = 0;
- while (pos != i - 1) {
- anterior = anterior->proximo;
- pos++;
- }
+ while (pos != i - 1) {
+ anterior = anterior->proximo;
+ pos++;
+ }
- pnoh aux = anterior->proximo;
- anterior->proximo = aux->proximo;
- lst->tamanho--;
+ pnoh aux = anterior->proximo;
+ anterior->proximo = aux->proximo;
+ lst->tamanho--;
- free(aux);
- }
- }
+ free(aux);
+ }
}
+ }
}
int indexLista(TLista lst, int dado) {
- int tam = lenLista(lst);
- int i, dadolst;
- pnoh no_dadolst;
+ int tam = lenLista(lst);
+ int i, dadolst;
+ pnoh no_dadolst;
- if (tam == 0) {
- return -1;
- }
+ if (tam == 0) {
+ return -1;
+ }
- i = 0;
+ i = 0;
+ no_dadolst = infoLista(lst, i);
+ dadolst = no_dadolst->dado;
+ while ((i < tam) && (dado != dadolst)) {
+ i++;
no_dadolst = infoLista(lst, i);
dadolst = no_dadolst->dado;
- while ((i < tam) && (dado != dadolst)) {
- i++;
- no_dadolst = infoLista(lst, i);
- dadolst = no_dadolst->dado;
- }
+ }
- if (i < tam) {
- return i;
- }
+ if (i < tam) {
+ return i;
+ }
- return -1;
+ return -1;
}
TLista clearLista(TLista lst) {
- int tam = lenLista(lst);
+ int tam = lenLista(lst);
- if (tam == 0) {
- return lst;
- }
+ if (tam == 0) {
+ return lst;
+ }
- while (lenLista(lst) > 0) {
- removeLista(lst, 0);
- }
+ while (lenLista(lst) > 0) {
+ removeLista(lst, 0);
+ }
- return lst;
+ return lst;
}
TLista clonaLista(TLista lst) {
- TLista clone = criaLista();
- int tam = lenLista(lst);
+ TLista clone = criaLista();
+ int tam = lenLista(lst);
- if (tam == 0) {
- return clone;
- }
+ if (tam == 0) {
+ return clone;
+ }
- for (int i = 0; i < tam; i++) {
- pnoh no = infoLista(lst, i);
- if (no != NULL) {
- appendLista(clone, no->dado);
- }
+ for (int i = 0; i < tam; i++) {
+ pnoh no = infoLista(lst, i);
+ if (no != NULL) {
+ appendLista(clone, no->dado);
}
+ }
- return clone;
+ return clone;
}
int main() {
- TLista lista = criaLista();
- appendLista(lista, 3);
- appendLista(lista, 5);
- appendLista(lista, 7);
-
- printf("Lista criada e adicionado 3 numeros\n");
- int tamanho = lenLista(lista);
- int primeiro = primLista(lista);
- int ultimo = ultLista(lista);
- pnoh valor = infoLista(lista, 1);
- int valor_dado = valor->dado;
- printf("Tamanho da lista: %d\nPrimeiro da Lista: %d\nUltimo da Lista: %d\nSegundo valor: %d\n", tamanho, primeiro, ultimo, valor_dado);
-
- insertLista(lista, 2, 6);
- valor = infoLista(lista, 2);
- valor_dado = valor->dado;
- printf("Adicionando 6 na posição 2: %d\n", valor_dado);
-
- removeLista(lista, 1);
- tamanho = lenLista(lista);
- printf("Novo tamanho após adicionar e remover: %d\n", tamanho);
-
- int index = indexLista(lista, 3);
- printf("Index do elemento com valor 3 na lista: %d\n", index);
-
- TLista cloneLista = clonaLista(lista);
- printf("Lista Duplicada\n");
-
- clearLista(lista);
- printf("Lista Apagada");
-
- return 0;
+ TLista lista = criaLista();
+ appendLista(lista, 3);
+ appendLista(lista, 5);
+ appendLista(lista, 7);
+
+ printf("Lista criada e adicionado 3 numeros\n");
+ int tamanho = lenLista(lista);
+ int primeiro = primLista(lista);
+ int ultimo = ultLista(lista);
+ pnoh valor = infoLista(lista, 1);
+ int valor_dado = valor->dado;
+ printf("Tamanho da lista: %d\nPrimeiro da Lista: %d\nUltimo da Lista: "
+ "%d\nSegundo valor: %d\n",
+ tamanho, primeiro, ultimo, valor_dado);
+
+ insertLista(lista, 2, 6);
+ valor = infoLista(lista, 2);
+ valor_dado = valor->dado;
+ printf("Adicionando 6 na posição 2: %d\n", valor_dado);
+
+ removeLista(lista, 1);
+ tamanho = lenLista(lista);
+ printf("Novo tamanho após adicionar e remover: %d\n", tamanho);
+
+ int index = indexLista(lista, 3);
+ printf("Index do elemento com valor 3 na lista: %d\n", index);
+
+ TLista cloneLista = clonaLista(lista);
+ printf("Lista Duplicada\n");
+
+ clearLista(lista);
+ printf("Lista Apagada");
+
+ return 0;
}
diff --git a/src/c/SortedLinkedList.c b/src/c/SortedLinkedList.c
index 29c37489..8fc5b4ff 100644
--- a/src/c/SortedLinkedList.c
+++ b/src/c/SortedLinkedList.c
@@ -1,6 +1,7 @@
/*
-* Exemplo de implementação de Lista Sequencial Ordenada em C - Utilizando sentinela
-*/
+ * Exemplo de implementação de Lista Sequencial Ordenada em C - Utilizando
+ *sentinela
+ */
#include
@@ -9,96 +10,105 @@
typedef int TIPOCHAVE; // Define um nome TIPOCHAVE para um tipo inteiro
-typedef struct{
- TIPOCHAVE chave;
-}REGISTRO;
-
-typedef struct{
- REGISTRO A[MAX+1]; // O +1 é a posição que será utilizada para a 'sentinela'
- int nroElementos;
-}LISTA;
-
-void inicializar(LISTA* L){
- L->nroElementos = 0; // Acessa a lista pelo endereço de memória
- int i = 0;
- for (i; i < MAX-2; ++i){ // Preenche a lista até -2 para deixar espaço para inserir mais depois
- L->A[i].chave = i*2;
- }
- L->nroElementos = MAX-2;
- // (*L).nroElementos = 0; // Neste caso iria acessar a lista em si, e não o ponteiro
+typedef struct {
+ TIPOCHAVE chave;
+} REGISTRO;
+
+typedef struct {
+ REGISTRO A[MAX + 1]; // O +1 é a posição que será utilizada para a 'sentinela'
+ int nroElementos;
+} LISTA;
+
+void inicializar(LISTA *L) {
+ L->nroElementos = 0; // Acessa a lista pelo endereço de memória
+ int i = 0;
+ for (i; i < MAX - 2; ++i) { // Preenche a lista até -2 para deixar espaço para
+ // inserir mais depois
+ L->A[i].chave = i * 2;
+ }
+ L->nroElementos = MAX - 2;
+ // (*L).nroElementos = 0; // Neste caso iria acessar a lista em si, e não o
+ // ponteiro
}
-/* A função do sentinela é adicionar a chave ao final da lista, ou seja,
+/* A função do sentinela é adicionar a chave ao final da lista, ou seja,
* sempre irá encontrar a chave, mesmo que seja na útlima posição da lista.
* Caso seja o último elemento, significa que não encontrou.
* Deste modo elimina o 'if' dentro do laço, poupando várias comparações
- */
-int buscaSentinela(TIPOCHAVE ch, LISTA* L){ // Poderia usar aqui busca binária, o que seria mais apropriado.
- int i = 0;
- L->A[L->nroElementos].chave = ch; // Atribui a 'chave'/valor buscado a ultima posição do array A
- while(L->A[i].chave != ch) // Percorre todo o array A buscando se a 'chave'/valor pesquisado se encontra no array (senão será o sentinela)
- i++;
- if(i == L->nroElementos) // Se o valor chegou até o final, significa que não encontrou o valor, retorna ERRO (-1)
- return ERRO;
- return i; // Caso contrário retorna a posição do valor/'chave' no array
+ */
+int buscaSentinela(
+ TIPOCHAVE ch,
+ LISTA *L) { // Poderia usar aqui busca binária, o que seria mais apropriado.
+ int i = 0;
+ L->A[L->nroElementos].chave =
+ ch; // Atribui a 'chave'/valor buscado a ultima posição do array A
+ while (L->A[i].chave !=
+ ch) // Percorre todo o array A buscando se a 'chave'/valor pesquisado
+ // se encontra no array (senão será o sentinela)
+ i++;
+ if (i == L->nroElementos) // Se o valor chegou até o final, significa que não
+ // encontrou o valor, retorna ERRO (-1)
+ return ERRO;
+ return i; // Caso contrário retorna a posição do valor/'chave' no array
}
-bool inserirOrdenado(REGISTRO reg, LISTA* L){
- int i = 0;
- if(L->nroElementos >= MAX)
- return false;
- L->A[L->nroElementos].chave = reg.chave;
- while(L->A[i].chave < reg.chave)
- i++;
- int p = L->nroElementos-1;
- while(p >= i){
- L->A[p+1] = L->A[p];
- p--;
- }
- L->A[i] = reg;
- L->nroElementos++;
- return true;
+bool inserirOrdenado(REGISTRO reg, LISTA *L) {
+ int i = 0;
+ if (L->nroElementos >= MAX)
+ return false;
+ L->A[L->nroElementos].chave = reg.chave;
+ while (L->A[i].chave < reg.chave)
+ i++;
+ int p = L->nroElementos - 1;
+ while (p >= i) {
+ L->A[p + 1] = L->A[p];
+ p--;
+ }
+ L->A[i] = reg;
+ L->nroElementos++;
+ return true;
}
-bool deletaValor(REGISTRO reg, LISTA* L){
- int posicao = buscaSentinela(reg.chave, L);
- if( posicao >= 0 ){
- for( posicao; posicao < L->nroElementos; posicao++ ){
- L->A[posicao] = L->A[posicao+1];
- }
- L->nroElementos--;
- return true;
- }else{
- return false;
- }
+bool deletaValor(REGISTRO reg, LISTA *L) {
+ int posicao = buscaSentinela(reg.chave, L);
+ if (posicao >= 0) {
+ for (posicao; posicao < L->nroElementos; posicao++) {
+ L->A[posicao] = L->A[posicao + 1];
+ }
+ L->nroElementos--;
+ return true;
+ } else {
+ return false;
+ }
}
-void mostraLista(LISTA* L){
- int i = 0;
- for (i; i < L->nroElementos; ++i){ // Percorre e mostra todos os valores do array
- printf("%d, ", L->A[i].chave);
- }
- printf("\n\n");
+void mostraLista(LISTA *L) {
+ int i = 0;
+ for (i; i < L->nroElementos;
+ ++i) { // Percorre e mostra todos os valores do array
+ printf("%d, ", L->A[i].chave);
+ }
+ printf("\n\n");
}
-int main(){
-
- LISTA LISTA;
- inicializar(&LISTA);
-
- printf("Valor 10 encontrado na posição: %d\n\n", buscaSentinela(10, &LISTA) );
- mostraLista(&LISTA);
-
- REGISTRO reg;
- reg.chave = 7;
- printf("Insere o valor: %d\n", reg.chave);
- inserirOrdenado(reg, &LISTA);
- mostraLista(&LISTA);
-
- reg.chave = 12;
- printf("Deleta o valor: %d\n", reg.chave);
- deletaValor(reg, &LISTA);
- mostraLista(&LISTA);
-
- return 0;
+int main() {
+
+ LISTA LISTA;
+ inicializar(&LISTA);
+
+ printf("Valor 10 encontrado na posição: %d\n\n", buscaSentinela(10, &LISTA));
+ mostraLista(&LISTA);
+
+ REGISTRO reg;
+ reg.chave = 7;
+ printf("Insere o valor: %d\n", reg.chave);
+ inserirOrdenado(reg, &LISTA);
+ mostraLista(&LISTA);
+
+ reg.chave = 12;
+ printf("Deleta o valor: %d\n", reg.chave);
+ deletaValor(reg, &LISTA);
+ mostraLista(&LISTA);
+
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/Stack.c b/src/c/Stack.c
index 4f91e9f4..e3b290dd 100644
--- a/src/c/Stack.c
+++ b/src/c/Stack.c
@@ -1,6 +1,6 @@
-/*
-* Exemplo de implementação de Pilha em C - Utiliza Sentinela
-*/
+/*
+ * Exemplo de implementação de Pilha em C - Utiliza Sentinela
+ */
#include
@@ -9,76 +9,76 @@
typedef int TIPOCHAVE;
-typedef struct{
- TIPOCHAVE chave;
-}REGISTRO;
+typedef struct {
+ TIPOCHAVE chave;
+} REGISTRO;
-typedef struct{
- REGISTRO A[MAX+1];
- int nroRegistros;
-}PILHA;
+typedef struct {
+ REGISTRO A[MAX + 1];
+ int nroRegistros;
+} PILHA;
-int inicializa(PILHA* p){
- p->nroRegistros = 0;
- int i = 0;
- for (i; i < MAX-2; i++){ // Preenche a Pilha *para testes
- p->A[i].chave = i*2; // É um array de REGISTRO (semelhante a class), poderia ter mais campos, por isso se define A[i].chave, irá inserir o valor no campo chave
- }
- p->nroRegistros = i;
+int inicializa(PILHA *p) {
+ p->nroRegistros = 0;
+ int i = 0;
+ for (i; i < MAX - 2; i++) { // Preenche a Pilha *para testes
+ p->A[i].chave = i * 2; // É um array de REGISTRO (semelhante a class),
+ // poderia ter mais campos, por isso se define
+ // A[i].chave, irá inserir o valor no campo chave
+ }
+ p->nroRegistros = i;
}
-bool inserePilha(int valor, PILHA* p){
- if( p->nroRegistros < MAX ){
- p->A[p->nroRegistros].chave = valor;
- p->nroRegistros++;
- return true;
- }else{
- return false;
- }
+bool inserePilha(int valor, PILHA *p) {
+ if (p->nroRegistros < MAX) {
+ p->A[p->nroRegistros].chave = valor;
+ p->nroRegistros++;
+ return true;
+ } else {
+ return false;
+ }
}
-bool removePilha(PILHA* p){
- p->nroRegistros--;
-}
+bool removePilha(PILHA *p) { p->nroRegistros--; }
-void mostraPilha(PILHA* p){
- int i = p->nroRegistros-1;
- printf("\nPilha:\n");
- for (i; i >= 0; i--){
- printf("%d = [ %d ]\n", i, p->A[i].chave);
- }
- printf("------------------\n");
+void mostraPilha(PILHA *p) {
+ int i = p->nroRegistros - 1;
+ printf("\nPilha:\n");
+ for (i; i >= 0; i--) {
+ printf("%d = [ %d ]\n", i, p->A[i].chave);
+ }
+ printf("------------------\n");
}
-int buscaPilha(int chave, PILHA* p){
- p->A[p->nroRegistros].chave = chave;
- int aux = 0;
- while( p->A[aux].chave != chave )
- aux++;
- if( aux == p->nroRegistros )
- return ERRO;
- return aux;
+int buscaPilha(int chave, PILHA *p) {
+ p->A[p->nroRegistros].chave = chave;
+ int aux = 0;
+ while (p->A[aux].chave != chave)
+ aux++;
+ if (aux == p->nroRegistros)
+ return ERRO;
+ return aux;
}
-int main(){
- PILHA vPilha;
- inicializa(&vPilha);
+int main() {
+ PILHA vPilha;
+ inicializa(&vPilha);
+
+ mostraPilha(&vPilha);
+ if (inserePilha(10, &vPilha)) {
+ printf("Inserido com sucesso");
+ } else {
+ printf("Pilha cheia");
+ }
+
+ mostraPilha(&vPilha);
+ removePilha(&vPilha);
+ mostraPilha(&vPilha);
- mostraPilha(&vPilha);
- if( inserePilha(10, &vPilha) ){
- printf("Inserido com sucesso");
- }else{
- printf("Pilha cheia");
- }
-
- mostraPilha(&vPilha);
- removePilha(&vPilha);
- mostraPilha(&vPilha);
-
- int aux = buscaPilha(8, &vPilha);
- if( aux != -1 ){
- printf("Valor 8 encontrado na posicao %d da pilha\n", aux);
- }else{
- printf("Valor nao encontrado\n");
- }
+ int aux = buscaPilha(8, &vPilha);
+ if (aux != -1) {
+ printf("Valor 8 encontrado na posicao %d da pilha\n", aux);
+ } else {
+ printf("Valor nao encontrado\n");
+ }
}
\ No newline at end of file
diff --git a/src/c/Timsort.c b/src/c/Timsort.c
index 51ab4c44..fba68ebc 100644
--- a/src/c/Timsort.c
+++ b/src/c/Timsort.c
@@ -2,127 +2,123 @@
const int THRESHOLD = 32;
-int is_odd(int n) {
- return n & 1;
-}
+int is_odd(int n) { return n & 1; }
int get_fmin(int a, int b) {
- if (a < b) {
- return a;
- }
- return b;
+ if (a < b) {
+ return a;
+ }
+ return b;
}
-int get_floor(int n) {
- return n / 2;
-}
+int get_floor(int n) { return n / 2; }
void print_array(int array[], int size) {
- printf("[");
- for (int i = 0; i < size; i++) {
- printf("%d", array[i]);
- if (i != size - 1) {
- printf(", ");
- }
+ printf("[");
+ for (int i = 0; i < size; i++) {
+ printf("%d", array[i]);
+ if (i != size - 1) {
+ printf(", ");
}
- printf("]\n");
+ }
+ printf("]\n");
}
int get_run_length(int size_of_array) {
- int run_length = size_of_array;
- int remainder = 0;
-
- while (run_length >= THRESHOLD) {
- if (is_odd(run_length)) {
- remainder = 1;
- }
- run_length = get_floor(run_length / 2);
+ int run_length = size_of_array;
+ int remainder = 0;
+
+ while (run_length >= THRESHOLD) {
+ if (is_odd(run_length)) {
+ remainder = 1;
}
- return run_length + remainder;
+ run_length = get_floor(run_length / 2);
+ }
+ return run_length + remainder;
}
void insertion_sort(int array[], int left_index, int right_index) {
- for (int i = left_index + 1; i <= right_index; i++) {
- int temp = array[i];
- int j = i - 1;
- while (j >= left_index && array[j] > temp) {
- array[j + 1] = array[j];
- j--;
- }
- array[j + 1] = temp;
+ for (int i = left_index + 1; i <= right_index; i++) {
+ int temp = array[i];
+ int j = i - 1;
+ while (j >= left_index && array[j] > temp) {
+ array[j + 1] = array[j];
+ j--;
}
+ array[j + 1] = temp;
+ }
}
-void merge_runs(int array[], int left_index, int middle_index, int right_index) {
- int left_size = middle_index - left_index + 1;
- int right_size = right_index - middle_index;
- int left[left_size];
- int right[right_size];
-
- for (int i = 0; i < left_size; i++) {
- left[i] = array[left_index + i];
- }
- for (int j = 0; j < right_size; j++) {
- right[j] = array[middle_index + 1 + j];
- }
-
- int i = 0;
- int j = 0;
- int k = left_index;
-
- while (i < left_size && j < right_size) {
- if (left[i] <= right[j]) {
- array[k] = left[i];
- i++;
- } else {
- array[k] = right[j];
- j++;
- }
- k++;
- }
-
- while (i < left_size) {
- array[k] = left[i];
- i++;
- k++;
- }
-
- while (j < right_size) {
- array[k] = right[j];
- j++;
- k++;
+void merge_runs(int array[], int left_index, int middle_index,
+ int right_index) {
+ int left_size = middle_index - left_index + 1;
+ int right_size = right_index - middle_index;
+ int left[left_size];
+ int right[right_size];
+
+ for (int i = 0; i < left_size; i++) {
+ left[i] = array[left_index + i];
+ }
+ for (int j = 0; j < right_size; j++) {
+ right[j] = array[middle_index + 1 + j];
+ }
+
+ int i = 0;
+ int j = 0;
+ int k = left_index;
+
+ while (i < left_size && j < right_size) {
+ if (left[i] <= right[j]) {
+ array[k] = left[i];
+ i++;
+ } else {
+ array[k] = right[j];
+ j++;
}
+ k++;
+ }
+
+ while (i < left_size) {
+ array[k] = left[i];
+ i++;
+ k++;
+ }
+
+ while (j < right_size) {
+ array[k] = right[j];
+ j++;
+ k++;
+ }
}
void timsort(int array[], int size) {
- int run_length = get_run_length(size);
-
- for (int i = 0; i < size; i += run_length) {
- insertion_sort(array, i, get_fmin((i + run_length - 1), (size - 1)));
- }
-
- for (int size_of_run = run_length; size_of_run < size; size_of_run *= 2) {
- for (int left_index = 0; left_index < size; left_index += 2 * size_of_run) {
- int middle_index = left_index + size_of_run - 1;
- int right_index = get_fmin((left_index + 2 * size_of_run - 1), (size - 1));
- merge_runs(array, left_index, middle_index, right_index);
- }
+ int run_length = get_run_length(size);
+
+ for (int i = 0; i < size; i += run_length) {
+ insertion_sort(array, i, get_fmin((i + run_length - 1), (size - 1)));
+ }
+
+ for (int size_of_run = run_length; size_of_run < size; size_of_run *= 2) {
+ for (int left_index = 0; left_index < size; left_index += 2 * size_of_run) {
+ int middle_index = left_index + size_of_run - 1;
+ int right_index =
+ get_fmin((left_index + 2 * size_of_run - 1), (size - 1));
+ merge_runs(array, left_index, middle_index, right_index);
}
+ }
}
int main() {
- int array[] = { 5, 2, -2147483648, 1, 4, 5323, -1, 0, 10, 9, 8, 7, 6, 2147483647, 4, 3, 2 };
- int size = sizeof(array) / sizeof(array[0]);
+ int array[] = {5, 2, -2147483648, 1, 4, 5323, -1, 0, 10,
+ 9, 8, 7, 6, 2147483647, 4, 3, 2};
+ int size = sizeof(array) / sizeof(array[0]);
- printf("Original array:\t");
- print_array(array, size);
+ printf("Original array:\t");
+ print_array(array, size);
- timsort(array, size);
+ timsort(array, size);
- printf("Sorted array:\t");
- print_array(array, size);
- return 0;
+ printf("Sorted array:\t");
+ print_array(array, size);
+ return 0;
}
-
-
-
diff --git a/src/c/TowerOfHanoi.c b/src/c/TowerOfHanoi.c
index 0e4affca..91ec0226 100644
--- a/src/c/TowerOfHanoi.c
+++ b/src/c/TowerOfHanoi.c
@@ -4,21 +4,18 @@ Torre de Hanoi em C
#include
-void hanoi(int pino0, int pino2, int pino1, int discos)
-{
- if (discos == 1)
- printf("Move de %i para %i\n", pino0, pino2);
+void hanoi(int pino0, int pino2, int pino1, int discos) {
+ if (discos == 1)
+ printf("Move de %i para %i\n", pino0, pino2);
- else
- {
- hanoi(pino0, pino1, pino2, discos - 1);
- hanoi(pino0, pino2, pino1, 1);
- hanoi(pino1, pino2, pino0, discos - 1);
- }
+ else {
+ hanoi(pino0, pino1, pino2, discos - 1);
+ hanoi(pino0, pino2, pino1, 1);
+ hanoi(pino1, pino2, pino0, discos - 1);
+ }
}
-int main()
-{
- hanoi(0, 2, 1, 3);
- return 0;
+int main() {
+ hanoi(0, 2, 1, 3);
+ return 0;
}
diff --git a/src/c/TravellingSalesman.c b/src/c/TravellingSalesman.c
index b7924423..d165ebe4 100644
--- a/src/c/TravellingSalesman.c
+++ b/src/c/TravellingSalesman.c
@@ -1,107 +1,116 @@
/*
-* Problema do Caixeiro Viajante em C
-* Utilizando uma matriz de distância para representar um grafo não direcionado.
-* Objetivo: Encontrar o menor caminho que passe por todos os vértices sem repetir nenhum, e chegar novamente ao vértice de início
-*
-* 6
-* (4)-----(0)
-* | \ / \
-* | \ 3/ \2
-* | \/ \
-* 3| /\ (1)
-* | / 3\ 4/ |
-* | / \ / |
-* (3)-----(2) |
-* | 7 |
-* | | 3
-* --------------
-*
-*
-* Matriz de Distância
-* 0 1 2 3 4
-* 0 0 2 - 3 6
-* 1 2 0 4 3 -
-* 2 - 4 0 7 3
-* 3 3 3 7 0 3
-* 4 6 - 3 3 0
-*
-*
-*/
+ * Traveling Salesman Problem in C
+ * Using a distance matrix to represent an undirected graph.
+ * Objective: Find the shortest path that visits all vertices without
+ *repeating any, and returns to the starting vertex.
+ *
+ * 6
+ * (4)-----(0)
+ * | \ / \
+ * | \ 3/ \2
+ * | \/ \
+ * 3| /\ (1)
+ * | / 3\ 4/ |
+ * | / \ / |
+ * (3)-----(2) |
+ * | 7 |
+ * | | 3
+ * --------------
+ *
+ * Distance Matrix
+ * 0 1 2 3 4
+ * 0 0 2 - 3 6
+ * 1 2 0 4 3 -
+ * 2 - 4 0 7 3
+ * 3 3 3 7 0 3
+ * 4 6 - 3 3 0
+ */
+#include
#include
#define VERTICES 5
-#define INFINITO 429496729
+#define INFINITY 429496729
-int tempSolucao[VERTICES];
-int melhorSolucao[VERTICES];
-bool visitados[VERTICES];
-int valorMelhorSolucao = INFINITO;
-int valorSolucaoAtual = 0;
+int tempSolution[VERTICES];
+int bestSolution[VERTICES];
+bool visited[VERTICES];
+int bestSolutionValue = INFINITY;
+int currentSolutionValue = 0;
-int matriz[VERTICES][VERTICES] = {{ 0, 2, INFINITO, 3, 6 },
- { 2, 0, 4, 3, INFINITO },
- { INFINITO, 4, 0, 7, 3 },
- { 3, 3, 7, 0, 3 },
- { 6, INFINITO, 3, 3, 0 }};
+int matrix[VERTICES][VERTICES] = {{0, 2, INFINITY, 3, 6},
+ {2, 0, 4, 3, INFINITY},
+ {INFINITY, 4, 0, 7, 3},
+ {3, 3, 7, 0, 3},
+ {6, INFINITY, 3, 3, 0}};
-void caixeiroViajanteAux(int x){
- // Se o valor da solução atual já estiver maior que o valor da melhor solução já para, pois já não pode mais ser a melhor solução
- if( valorSolucaoAtual > valorMelhorSolucao )
- return;
+void travelingSalesmanAux(int x) {
+ // If the current solution value is already greater than the best solution,
+ // stop as it can't be the best solution
+ if (currentSolutionValue > bestSolutionValue)
+ return;
- if( x == VERTICES ){ // Se x == VERTICES significa que o vetor da solução temporária está completo
- int distancia = matriz[tempSolucao[x-1]][tempSolucao[0]];
- // Se encontrou uma solução melhor/menor
- if( distancia < INFINITO && valorSolucaoAtual + distancia < valorMelhorSolucao ){
- valorMelhorSolucao = valorSolucaoAtual + distancia; // Substitui a melhor solução pela melhor encontrada agora
- // Copia todo o vetor de solução temporária para o vetor de melhor solução encontrada
- for (int i = 0; i < VERTICES; ++i){
- melhorSolucao[i] = tempSolucao[i];
- }
- }
- return;
- }
-
- int ultimo = tempSolucao[x-1]; // Ultimo recebe o número do último vértice que se encontra na solução temporária
- // For que percorre todas as colunas da matriz na linha do último vértice do vetor solução temporária
- for (int i = 0; i < VERTICES; i++){
- // Se a posição i do vetor ainda não foi visitada, e se o valor da matriz na posição é menor que INFINITO
- if( visitados[i] == false && matriz[ultimo][i] < INFINITO ){
- visitados[i] = true; // Marca como visitado
- tempSolucao[x] = i; // Carrega o vértice que está passando no vetor de solução temporária
- valorSolucaoAtual += matriz[ultimo][i]; // Incrementa o valor da matriz na variável que guarda o total do caminho percorrido
- caixeiroViajanteAux(x+1); // Chama recursivamente para o próximo vértice
- valorSolucaoAtual -= matriz[ultimo][i]; // Se ainda não terminou, diminuí o valor da váriavel que guarda o total da solução atual
- visitados[i] = false; // Seta como false a posição para poder ser utilizado por outro vértice
- }
-
- }
+ if (x == VERTICES) { // If x == VERTICES, it means the temporary solution
+ // array is complete
+ int distance = matrix[tempSolution[x - 1]][tempSolution[0]];
+ // If a better (shorter) solution is found
+ if (distance < INFINITY &&
+ currentSolutionValue + distance < bestSolutionValue) {
+ bestSolutionValue =
+ currentSolutionValue +
+ distance; // Update the best solution with the new better one
+ // Copy the entire temporary solution array to the best solution array
+ for (int i = 0; i < VERTICES; ++i) {
+ bestSolution[i] = tempSolution[i];
+ }
+ }
+ return;
+ }
+ int last = tempSolution[x - 1]; // 'last' holds the number of the last vertex
+ // in the temporary solution array
+ // Loop through all columns in the matrix on the row of the last vertex in the
+ // temporary solution array
+ for (int i = 0; i < VERTICES; i++) {
+ // If the i-th vertex hasn't been visited, and the matrix value is less than
+ // INFINITY
+ if (!visited[i] && matrix[last][i] < INFINITY) {
+ visited[i] = true; // Mark as visited
+ tempSolution[x] =
+ i; // Add the current vertex to the temporary solution array
+ currentSolutionValue += matrix[last][i]; // Increment the path total
+ travelingSalesmanAux(x + 1); // Recursively call for the next vertex
+ currentSolutionValue -=
+ matrix[last][i]; // Decrease the path total if not finished yet
+ visited[i] = false; // Mark the vertex as unvisited so it can be used
+ // again by another vertex
+ }
+ }
}
-void caixeiroViajante(int inicial){
- visitados[inicial] = true; // Marca o primeiro vértice como visitado (0)
- tempSolucao[0] = inicial; // Coloca o vértice 0 na primeira posição do vetor de solução temporária
- caixeiroViajanteAux(1); // Chama o método auxiliar do caixeiro viajante
+void travelingSalesman(int start) {
+ visited[start] = true; // Mark the starting vertex as visited (0)
+ tempSolution[0] = start; // Place vertex 0 in the first position of the
+ // temporary solution array
+ travelingSalesmanAux(
+ 1); // Call the auxiliary function for the traveling salesman problem
}
-void iniciaVetores(){
- for (int i = 0; i < VERTICES; i++){
- visitados[i] = false;
- tempSolucao[i] = -1;
- melhorSolucao[i] = -1;
- }
+void initializeArrays() {
+ for (int i = 0; i < VERTICES; i++) {
+ visited[i] = false;
+ tempSolution[i] = -1;
+ bestSolution[i] = -1;
+ }
}
-int main(){
+int main() {
+ initializeArrays();
+ travelingSalesman(0);
- iniciaVetores();
- caixeiroViajante(0);
-
- printf("Caminho mínimo: %d\n", valorMelhorSolucao);
- for (int i = 0; i < VERTICES; i++){
- printf("%d, ", melhorSolucao[i]);
- }
- printf("\n\n");
-}
\ No newline at end of file
+ printf("Minimum path cost: %d\n", bestSolutionValue);
+ for (int i = 0; i < VERTICES; i++) {
+ printf("%d, ", bestSolution[i]);
+ }
+ printf("\n\n");
+}
diff --git a/src/c/TwoSum.c b/src/c/TwoSum.c
index 65162435..ec52ae66 100644
--- a/src/c/TwoSum.c
+++ b/src/c/TwoSum.c
@@ -1,61 +1,59 @@
/*
TwoSum Algorithm in C
- Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
-
- You may assume that each input would have exactly one solution, and you may not use the same element twice.
-
- You can return the answer in any order.
+ Given an array of integers nums and an integer target, return indices of
+the two numbers such that they add up to target.
+
+ You may assume that each input would have exactly one solution, and you
+may not use the same element twice.
+
+ You can return the answer in any order.
*/
#include
#include
-int* twoSum(int* nums, int numsSize, int target){
-
- for(int i=0;i
#include
+#include
#define ERRO -1
typedef int TIPOCHAVE;
-typedef struct aux{
- TIPOCHAVE chave;
- struct aux *prox;
-}REGISTRO, *PONT;
+typedef struct aux {
+ TIPOCHAVE chave;
+ struct aux *prox;
+} REGISTRO, *PONT;
-PONT criaRegistro(TIPOCHAVE ch){
- PONT rg = (PONT) malloc( sizeof(PONT) );
- rg->chave = ch;
- rg->prox = NULL;
- return rg;
+PONT criaRegistro(TIPOCHAVE ch) {
+ PONT rg = (PONT)malloc(sizeof(PONT));
+ rg->chave = ch;
+ rg->prox = NULL;
+ return rg;
}
-PONT insereRegistro(TIPOCHAVE ch, PONT rg){
- if( rg == NULL )
- return criaRegistro(ch); // Se não tem nenhum registro na lista cria um novo
- while( rg->prox != NULL )
- rg = rg->prox;
- rg->prox = criaRegistro(ch);
- return NULL;
+PONT insereRegistro(TIPOCHAVE ch, PONT rg) {
+ if (rg == NULL)
+ return criaRegistro(ch); // Se não tem nenhum registro na lista cria um novo
+ while (rg->prox != NULL)
+ rg = rg->prox;
+ rg->prox = criaRegistro(ch);
+ return NULL;
}
-void mostraLista(PONT rg){
- if( rg == NULL ) return;
- printf("%d, ", rg->chave);
- mostraLista(rg->prox);
+void mostraLista(PONT rg) {
+ if (rg == NULL)
+ return;
+ printf("%d, ", rg->chave);
+ mostraLista(rg->prox);
}
-PONT buscaSequencial(TIPOCHAVE ch, PONT rg){
- while( rg != NULL ){
- if( rg->chave == ch )
- return rg;
- rg = rg->prox;
- }
- return NULL;
+PONT buscaSequencial(TIPOCHAVE ch, PONT rg) {
+ while (rg != NULL) {
+ if (rg->chave == ch)
+ return rg;
+ rg = rg->prox;
+ }
+ return NULL;
}
-bool deletaRegistro(TIPOCHAVE ch, PONT rg){
- PONT ant;
- while( rg != NULL ){
- if( rg->chave == ch ){
- ant->prox = rg->prox;
- free(rg);
- return true;
- }
- ant = rg;
- rg = rg->prox;
- }
- printf("\nChave %d não encontrada.\n",ch);
- return false;
+bool deletaRegistro(TIPOCHAVE ch, PONT rg) {
+ PONT ant;
+ while (rg != NULL) {
+ if (rg->chave == ch) {
+ ant->prox = rg->prox;
+ free(rg);
+ return true;
+ }
+ ant = rg;
+ rg = rg->prox;
+ }
+ printf("\nChave %d não encontrada.\n", ch);
+ return false;
}
-int main(){
- PONT RG = insereRegistro(23, RG);
- insereRegistro(34, RG);
- insereRegistro(12, RG);
- insereRegistro(63, RG);
- insereRegistro(45, RG);
+int main() {
+ PONT RG = insereRegistro(23, RG);
+ insereRegistro(34, RG);
+ insereRegistro(12, RG);
+ insereRegistro(63, RG);
+ insereRegistro(45, RG);
+
+ mostraLista(RG);
- mostraLista(RG);
+ TIPOCHAVE ch = 64;
+ if (buscaSequencial(ch, RG) != NULL)
+ printf("\nEncontrou chave %d\n", ch);
+ else
+ printf("\nNão encontrou chave %d\n", ch);
- TIPOCHAVE ch = 64;
- if( buscaSequencial(ch, RG) != NULL )
- printf("\nEncontrou chave %d\n", ch);
- else
- printf("\nNão encontrou chave %d\n", ch);
+ deletaRegistro(63, RG);
+ mostraLista(RG);
- deletaRegistro(63, RG);
- mostraLista(RG);
-
- printf("\n");
- deletaRegistro(34, RG);
- mostraLista(RG);
- return 0;
+ printf("\n");
+ deletaRegistro(34, RG);
+ mostraLista(RG);
+ return 0;
}
\ No newline at end of file
diff --git a/src/cpp/BinarySearch.cpp b/src/cpp/BinarySearch.cpp
index dcc7e6fc..5e7d778c 100644
--- a/src/cpp/BinarySearch.cpp
+++ b/src/cpp/BinarySearch.cpp
@@ -3,52 +3,39 @@
using namespace std;
-int binarySearch(int value, vector &vec, int leftIndex, int rightIndex)
-{
- int mid = (leftIndex + rightIndex) / 2;
-
- if (leftIndex <= rightIndex)
- {
- if (value > vec[mid])
- {
- leftIndex = mid + 1;
- return binarySearch(value, vec, leftIndex, rightIndex);
- }
- else if (value < vec[mid])
- {
- rightIndex = mid - 1;
- return binarySearch(value, vec, leftIndex, rightIndex);
- }
- else
- {
- return mid;
- }
- }
- else
- {
- return -1;
+int binarySearch(int value, vector &vec, int leftIndex, int rightIndex) {
+ int mid = (leftIndex + rightIndex) / 2;
+
+ if (leftIndex <= rightIndex) {
+ if (value > vec[mid]) {
+ leftIndex = mid + 1;
+ return binarySearch(value, vec, leftIndex, rightIndex);
+ } else if (value < vec[mid]) {
+ rightIndex = mid - 1;
+ return binarySearch(value, vec, leftIndex, rightIndex);
+ } else {
+ return mid;
}
+ } else {
+ return -1;
+ }
}
-int main()
-{
- vector vec;
-
- for (int index = 1; index <= 50; index++)
- {
- vec.push_back(index);
- }
+int main() {
+ vector vec;
- int value = 45;
+ for (int index = 1; index <= 50; index++) {
+ vec.push_back(index);
+ }
- int index = binarySearch(value, vec, 0, vec.size());
+ int value = 45;
- if (index >= 0)
- {
- cout << "Value " << to_string(value) << " found at position " << to_string(index) << endl;
- }
- else
- {
- cout << "Could not find the value " << to_string(value) << endl;
- }
+ int index = binarySearch(value, vec, 0, vec.size());
+
+ if (index >= 0) {
+ cout << "Value " << to_string(value) << " found at position "
+ << to_string(index) << endl;
+ } else {
+ cout << "Could not find the value " << to_string(value) << endl;
+ }
}
\ No newline at end of file
diff --git a/src/cpp/BinarySearchTree.cpp b/src/cpp/BinarySearchTree.cpp
index ddc01eb4..9973dc0a 100644
--- a/src/cpp/BinarySearchTree.cpp
+++ b/src/cpp/BinarySearchTree.cpp
@@ -4,9 +4,9 @@
* Structure for a binary tree node
*/
struct Node {
- int data; ///< The integer data value stored in the node.
- Node *left; ///< Pointer to the left child node.
- Node *right; ///< Pointer to the right child node.
+ int data; ///< The integer data value stored in the node.
+ Node *left; ///< Pointer to the left child node.
+ Node *right; ///< Pointer to the right child node.
/**
* Constructor to create a new node with the given data.
@@ -17,7 +17,7 @@ struct Node {
};
class BinarySearchTree {
- public:
+public:
BinarySearchTree() : root(nullptr) {}
Node *find(int x) const { return _find(this->root, x); }
@@ -32,7 +32,7 @@ class BinarySearchTree {
void postorderTraversal() const { _printPostorder(this->root); }
- private:
+private:
Node *root;
/**
diff --git a/src/cpp/BinaryTree.cpp b/src/cpp/BinaryTree.cpp
new file mode 100644
index 00000000..3f77440a
--- /dev/null
+++ b/src/cpp/BinaryTree.cpp
@@ -0,0 +1,110 @@
+#include
+
+using namespace std;
+
+// Create a class for the BinaryTree
+class BinaryTree {
+ // Create a struct for the TreeNode
+ struct TreeNode {
+ // Variables for the TreeNode
+ int data;
+ TreeNode *left;
+ TreeNode *right;
+
+ // Constructor for the TreeNode
+ TreeNode(int value) : data(value), left(nullptr), right(nullptr) {}
+ };
+
+ // Private Variables and Functions
+private:
+ TreeNode *root;
+
+ // Insert Function
+ TreeNode *insert(TreeNode *root, int value) {
+ if (root == nullptr)
+ return new TreeNode(value);
+
+ if (value < root->data)
+ root->left = insert(root->left, value);
+ else
+ root->right = insert(root->right, value);
+
+ return root;
+ }
+
+ // Print Inorder Function
+ void printInorder(TreeNode *head) {
+ if (head != nullptr) {
+ printInorder(head->left);
+ cout << head->data << " ";
+ printInorder(head->right);
+ }
+ }
+
+ // Print Preorder Function
+ void printPreorder(TreeNode *head) {
+ if (head != nullptr) {
+ cout << head->data << " ";
+ printPreorder(head->left);
+ printPreorder(head->right);
+ }
+ }
+
+ // Print Postorder Function
+ void printPostorder(TreeNode *head) {
+ if (head != nullptr) {
+ printPostorder(head->left);
+ printPostorder(head->right);
+ cout << head->data << " ";
+ }
+ }
+
+ // Public Functions
+public:
+ // Constructor
+ BinaryTree() : root(nullptr) {}
+
+ // Insert Function
+ void insert(int value) { root = insert(root, value); }
+
+ // Print Inorder Function
+ void printInorder() {
+ printInorder(root);
+ cout << endl;
+ }
+
+ // Print Preorder Function
+ void printPreorder() {
+ printPreorder(root);
+ cout << endl;
+ }
+
+ // Print Postorder Function
+ void printPostorder() {
+ printPostorder(root);
+ cout << endl;
+ }
+};
+
+int main() {
+ // Create tree
+ BinaryTree binaryTree;
+
+ binaryTree.insert(10);
+ binaryTree.insert(6);
+ binaryTree.insert(15);
+ binaryTree.insert(3);
+ binaryTree.insert(8);
+ binaryTree.insert(20);
+
+ cout << "InOrder: ";
+ binaryTree.printInorder();
+
+ cout << "PreOrder: ";
+ binaryTree.printPreorder();
+
+ cout << "PostOrder: ";
+ binaryTree.printPostorder();
+
+ return 0;
+}
diff --git a/src/cpp/BubbleSort.cpp b/src/cpp/BubbleSort.cpp
index 80614b00..5d4dafaa 100644
--- a/src/cpp/BubbleSort.cpp
+++ b/src/cpp/BubbleSort.cpp
@@ -3,45 +3,37 @@
using namespace std;
-vector bubbleSort(vector vector)
-{
- for (uint32_t end = vector.size()-1; end > 0; --end)
- {
- for (uint32_t index = 0; index < end; ++index)
- {
- if (vector[index] > vector[index+1])
- {
- int temp = vector[index];
- vector[index] = vector[index+1];
- vector[index+1] = temp;
- }
- }
+vector bubbleSort(vector vector) {
+ for (uint32_t end = vector.size() - 1; end > 0; --end) {
+ for (uint32_t index = 0; index < end; ++index) {
+ if (vector[index] > vector[index + 1]) {
+ int temp = vector[index];
+ vector[index] = vector[index + 1];
+ vector[index + 1] = temp;
+ }
}
- return vector;
+ }
+ return vector;
}
-void showVector(vector vector)
-{
- for (uint32_t i = 0; i < vector.size(); ++i)
- {
- if (i +1 == vector.size())
- cout << vector[i];
- else
- cout << vector[i] << ", ";
- }
- cout << "\n";
+void showVector(vector vector) {
+ for (uint32_t i = 0; i < vector.size(); ++i) {
+ if (i + 1 == vector.size())
+ cout << vector[i];
+ else
+ cout << vector[i] << ", ";
+ }
+ cout << "\n";
}
-int main()
-{
- vector vector;
- for (uint32_t i = 0; i < 10; ++i)
- {
- vector.push_back(rand() % 100);
- }
- cout << "Initial Vector: ";
- showVector(vector);
- vector = bubbleSort(vector);
- cout << "Sorted Vector: ";
- showVector(vector);
+int main() {
+ vector vector;
+ for (uint32_t i = 0; i < 10; ++i) {
+ vector.push_back(rand() % 100);
+ }
+ cout << "Initial Vector: ";
+ showVector(vector);
+ vector = bubbleSort(vector);
+ cout << "Sorted Vector: ";
+ showVector(vector);
}
diff --git a/src/cpp/CalculatePi.cpp b/src/cpp/CalculatePi.cpp
index bbdb28db..25f92878 100644
--- a/src/cpp/CalculatePi.cpp
+++ b/src/cpp/CalculatePi.cpp
@@ -5,19 +5,16 @@ float pi = 0.0;
float denominator = 1.0;
float operation = 1.0;
-float pi_calculator(int terms)
-{
- for (int i = 0; i < terms; i++)
- {
- pi += operation * (4.0 / denominator);
- denominator += 2.0;
- operation *= -1.0;
- }
- return pi;
+float pi_calculator(int terms) {
+ for (int i = 0; i < terms; i++) {
+ pi += operation * (4.0 / denominator);
+ denominator += 2.0;
+ operation *= -1.0;
+ }
+ return pi;
}
-int main()
-{
- float result = pi_calculator(100000);
- cout << result;
+int main() {
+ float result = pi_calculator(100000);
+ cout << result;
}
diff --git a/src/cpp/ConnectedComponents.cpp b/src/cpp/ConnectedComponents.cpp
new file mode 100644
index 00000000..050222e3
--- /dev/null
+++ b/src/cpp/ConnectedComponents.cpp
@@ -0,0 +1,46 @@
+#include
+#include
+
+#define VERTICES 6
+#define INF -1
+
+std::vector visited(VERTICES, false); // Array to track visited vertices
+int components = 0;
+
+// Adjacency matrix representing the graph
+int matrix[VERTICES][VERTICES] = {
+ {0, INF, 1, INF, INF, INF}, {INF, 0, INF, 1, 1, INF},
+ {1, INF, 0, INF, INF, INF}, {INF, 1, INF, 0, 1, 1},
+ {INF, 1, INF, 1, 0, 1}, {INF, INF, INF, 1, 1, 0}};
+
+// Recursive method to find connected components using adjacency matrix
+void findConnectedComponents(int current) {
+ for (int i = 0; i < VERTICES; i++) {
+ if (!visited[i] && matrix[current][i] == 1) {
+ visited[i] = true;
+ components++;
+ std::cout << "(" << i << ")-";
+ findConnectedComponents(i);
+ }
+ }
+}
+
+int main() {
+ // Initialize all vertices as unvisited
+ for (int i = 0; i < VERTICES; i++)
+ visited[i] = false;
+
+ // For each vertex, if it is unvisited, start a DFS and count components
+ for (int i = 0; i < VERTICES; i++) {
+ if (!visited[i]) {
+ components = 0;
+ visited[i] = true;
+ std::cout << "Starting at vertex (" << i << ")-";
+ findConnectedComponents(i);
+ std::cout << "\nNumber of connected components starting from vertex " << i
+ << ": " << components << "\n\n";
+ }
+ }
+
+ return 0;
+}
diff --git a/src/cpp/CountingSort.cpp b/src/cpp/CountingSort.cpp
index 400b6a54..1a6733fa 100644
--- a/src/cpp/CountingSort.cpp
+++ b/src/cpp/CountingSort.cpp
@@ -1,107 +1,105 @@
+#include
#include
#include
-#include
using namespace std;
-vector counting_sort(vector& nums) {
-
-
- // nums = {5, 0, 1, 2, 3, 5, 3, 0, 9, 4}
- // max = 9
- // The vector contains numbers between [0 .. max]
- auto max = *max_element(nums.begin(), nums.end());
-
-
- // Creates a vector with max + 1 positions to count occurrences of each element
- // 0 1 2 3 4 5 6 7 8 9 -> possible elements to occur in the vector nums
- // Counting = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
- vector counting(max+1);
-
-
- // Counts occurrences of each element
- // nums = {5, 0, 1, 2, 3, 5, 3, 0, 9, 4}
- //
- // 0 1 2 3 4 5 6 7 8 9
- // counting = {2, 1, 1, 2, 1, 2, 0, 0, 0, 1}
- //
- for(auto& i : nums) {
- counting[i]++;
- }
-
-
- // Now, counting = {2, 3, 4, 6, 7, 9, 9, 9, 9, 10}
- // It will be used to determine the positions of the elements in the ordered vector
- for (size_t i = 1; i < counting.size(); i++) {
-
- counting[i] += counting[i-1];
- }
-
- vector sorted(nums.size());
-
- /*
-
- The next loop places the numbers in their proper positions in the ordered vector
- i = iterates through the elements of nums
- counting[i] -1 is the position that element i must assume in the ordered vector
-
- The first 3 steps would be:
-
- nums = {5, 0, 1, 2, 3, 5, 3, 0, 9, 4}
- counting = {2, 3, 4, 6, 7, 9, 9, 9, 9, 10}
- sorted = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
-
- Step 1:
- i = 5
- counting[i] => counting[5] => 9
- sorted[9 - 1] => sorted[8] = i => sorted[8] = 5
- sorted = {0, 0, 0, 0, 0, 0, 0, 0, 5, 0}
-
- Step 2:
- i = 0
- counting[i] => counting[0] => 2
- sorted[2 - 1] => sorted[1] = i => sorted[1] = 0
- sorted = {0, 0, 0, 0, 0, 0, 0, 0, 5, 0}
-
- Step 3:
- i = 1
- counting[i] => counting[1] => 3
- sorted[3 - 1] => sorted[2] = i => sorted[2] = 1
- sorted = {0, 0, 1, 0, 0, 0, 0, 0, 5, 0}
- */
- for(auto& i : nums) {
- sorted[ counting[i]-1 ] = i;
- counting[i]--;
- }
-
- return sorted;
+vector counting_sort(vector &nums) {
+
+ // nums = {5, 0, 1, 2, 3, 5, 3, 0, 9, 4}
+ // max = 9
+ // The vector contains numbers between [0 .. max]
+ auto max = *max_element(nums.begin(), nums.end());
+
+ // Creates a vector with max + 1 positions to count occurrences of each
+ // element
+ // 0 1 2 3 4 5 6 7 8 9 -> possible elements to occur in
+ // the vector nums
+ // Counting = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
+ vector counting(max + 1);
+
+ // Counts occurrences of each element
+ // nums = {5, 0, 1, 2, 3, 5, 3, 0, 9, 4}
+ //
+ // 0 1 2 3 4 5 6 7 8 9
+ // counting = {2, 1, 1, 2, 1, 2, 0, 0, 0, 1}
+ //
+ for (auto &i : nums) {
+ counting[i]++;
+ }
+
+ // Now, counting = {2, 3, 4, 6, 7, 9, 9, 9, 9, 10}
+ // It will be used to determine the positions of the elements in the ordered
+ // vector
+ for (size_t i = 1; i < counting.size(); i++) {
+
+ counting[i] += counting[i - 1];
+ }
+
+ vector sorted(nums.size());
+
+ /*
+
+ The next loop places the numbers in their proper positions in the ordered
+ vector i = iterates through the elements of nums counting[i] -1 is the
+ position that element i must assume in the ordered vector
+
+ The first 3 steps would be:
+
+ nums = {5, 0, 1, 2, 3, 5, 3, 0, 9, 4}
+ counting = {2, 3, 4, 6, 7, 9, 9, 9, 9, 10}
+ sorted = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
+
+ Step 1:
+ i = 5
+ counting[i] => counting[5] => 9
+ sorted[9 - 1] => sorted[8] = i => sorted[8] = 5
+ sorted = {0, 0, 0, 0, 0, 0, 0, 0, 5, 0}
+
+ Step 2:
+ i = 0
+ counting[i] => counting[0] => 2
+ sorted[2 - 1] => sorted[1] = i => sorted[1] = 0
+ sorted = {0, 0, 0, 0, 0, 0, 0, 0, 5, 0}
+
+ Step 3:
+ i = 1
+ counting[i] => counting[1] => 3
+ sorted[3 - 1] => sorted[2] = i => sorted[2] = 1
+ sorted = {0, 0, 1, 0, 0, 0, 0, 0, 5, 0}
+ */
+ for (auto &i : nums) {
+ sorted[counting[i] - 1] = i;
+ counting[i]--;
+ }
+
+ return sorted;
}
void print_vector(vector vec) {
- cout << "[";
- for (size_t i = 0; i < vec.size(); i++) {
- if(i != vec.size()-1) {
- cout << vec[i] << ", ";
- }
- else {
- cout << vec[i];
- }
+ cout << "[";
+ for (size_t i = 0; i < vec.size(); i++) {
+ if (i != vec.size() - 1) {
+ cout << vec[i] << ", ";
+ } else {
+ cout << vec[i];
}
- cout << "]" << endl;
+ }
+ cout << "]" << endl;
}
int main() {
- vector nums{5, 0, 1, 2, 3, 5, 3, 0, 9, 4};
+ vector nums{5, 0, 1, 2, 3, 5, 3, 0, 9, 4};
- vector sorted = counting_sort(nums);
+ vector sorted = counting_sort(nums);
- cout << "Original vector = ";
- print_vector(nums);
+ cout << "Original vector = ";
+ print_vector(nums);
- cout << "Sorted vector = ";
- print_vector(sorted);
+ cout << "Sorted vector = ";
+ print_vector(sorted);
- return 0;
+ return 0;
}
diff --git a/src/cpp/Dijkstras_MinHeap.cpp b/src/cpp/Dijkstras_MinHeap.cpp
new file mode 100644
index 00000000..13ff75bb
--- /dev/null
+++ b/src/cpp/Dijkstras_MinHeap.cpp
@@ -0,0 +1,101 @@
+/**
+ * Dijkstras_MinHeap.cpp
+ *
+ * This file implements Dijkstra's algorithm using a min-heap (priority queue).
+ * The algorithm finds the shortest paths from the source vertex to all other
+ * vertices in a weighted graph.
+ *
+ * Functions:
+ * - void dijkstra(const unordered_map>& graph, int
+ * start_vertex)
+ * - graph: An adjacency list representation of the graph.
+ * - key: vertex
+ * - value: unordered_map of connected vertices and their edge weights
+ * - start_vertex: The starting vertex for Dijkstra's algorithm.
+ *
+ * Example Usage:
+ * Uncomment the main function to run a sample test case.
+ * The sample graph used in the main function is represented as an adjacency
+ * list.
+ */
+
+#include
+#include
+#include
+#include
+#include
+
+using namespace std;
+
+// A structure to represent a node in the priority queue
+struct Node {
+ int vertex;
+ int distance;
+ bool operator>(const Node &other) const { return distance > other.distance; }
+};
+
+void dijkstra(const unordered_map> &graph,
+ int start_vertex) {
+ // Initialize distances and predecessors
+ unordered_map dist;
+ unordered_map pred;
+ for (const auto &pair : graph) {
+ dist[pair.first] = numeric_limits::max();
+ pred[pair.first] = -1;
+ }
+ dist[start_vertex] = 0;
+
+ // Priority queue to store vertices and their distances
+ priority_queue, greater> priority_queue;
+ priority_queue.push({start_vertex, 0});
+
+ while (!priority_queue.empty()) {
+ Node current = priority_queue.top();
+ priority_queue.pop();
+
+ // If this distance is not updated, continue
+ if (current.distance > dist[current.vertex]) {
+ continue;
+ }
+
+ // Visit each neighbor of the current vertex
+ for (const auto &neighbor_pair : graph.at(current.vertex)) {
+ int neighbor = neighbor_pair.first;
+ int weight = neighbor_pair.second;
+ int distance = current.distance + weight;
+
+ // If a shorter path to the neighbor is found
+ if (distance < dist[neighbor]) {
+ dist[neighbor] = distance;
+ pred[neighbor] = current.vertex;
+ priority_queue.push({neighbor, distance});
+ }
+ }
+ }
+
+ // Print distances and predecessors
+ cout << "Distances: \n";
+ for (const auto &pair : dist) {
+ cout << "Vertex " << pair.first << ": " << pair.second << endl;
+ }
+ cout << "\nPredecessors: \n";
+ for (const auto &pair : pred) {
+ cout << "Vertex " << pair.first << ": " << pair.second << endl;
+ }
+}
+
+// Uncomment the following main function to run a sample test case
+
+int main() {
+ // Example graph represented as an adjacency list
+ unordered_map> graph = {
+ {0, {{1, 1}, {2, 4}}},
+ {1, {{0, 1}, {2, 2}, {3, 5}}},
+ {2, {{0, 4}, {1, 2}, {3, 1}}},
+ {3, {{1, 5}, {2, 1}}}};
+
+ // Running Dijkstra's algorithm from vertex 0
+ dijkstra(graph, 0);
+
+ return 0;
+}
diff --git a/src/cpp/DoublyLinkedList.cpp b/src/cpp/DoublyLinkedList.cpp
index f75e2b9b..15dc333f 100644
--- a/src/cpp/DoublyLinkedList.cpp
+++ b/src/cpp/DoublyLinkedList.cpp
@@ -1,223 +1,190 @@
#include
-class Node
-{
+class Node {
private:
- int value;
+ int value;
public:
- Node *next{nullptr};
- Node *previous{nullptr};
+ Node *next{nullptr};
+ Node *previous{nullptr};
- // Node constructor
- Node(int value)
- {
- this->value = value;
- }
+ // Node constructor
+ Node(int value) { this->value = value; }
- int getValue() { return this->value; };
+ int getValue() { return this->value; };
};
-class DoublyLinkedList
-{
+class DoublyLinkedList {
private:
- Node *first{nullptr};
-
- // Receives the node reference and make the pointers around stop pointing to
- void remove_pointers_to(Node *&node)
- {
- if (node->next)
- {
- node->next->previous = node->previous;
- }
- if (node->previous)
- {
- node->previous->next = node->next;
- }
- else
- {
- this->first = node->next;
- }
+ Node *first{nullptr};
+
+ // Receives the node reference and make the pointers around stop pointing to
+ void remove_pointers_to(Node *&node) {
+ if (node->next) {
+ node->next->previous = node->previous;
+ }
+ if (node->previous) {
+ node->previous->next = node->next;
+ } else {
+ this->first = node->next;
}
+ }
public:
- DoublyLinkedList() {}
-
- void push_front(int value)
- {
- // Initialize a pointier to a new node with received value
- Node *node = new Node(value);
- // Node points to the first
- node->next = this->first;
-
- // If there is a first node, make him point to new node
- if (this->first)
- {
- this->first->previous = node;
- }
-
- // Node becomes the first
- this->first = node;
- }
-
- // Checks if there is a first node
- bool isEmpty()
- {
- if (!this->first)
- {
- return true;
- }
- return false;
- }
-
- void push_back(int value)
- {
- Node *node = new Node(value);
- Node *selectedNode = this->first;
-
- if (this->isEmpty())
- {
- this->first = node;
- return;
- }
-
- Node *aux{nullptr};
- while (selectedNode)
- {
- aux = selectedNode;
- selectedNode = selectedNode->next;
- }
-
- node->previous = aux;
- aux->next = node;
- };
-
- void remove(int value)
- {
- // Throw exception to empty List
- if (this->isEmpty())
- {
- throw std::logic_error("List is empty, nothing to be removed!");
- }
-
- // Initialize a pointier to first element
- Node *node = this->first;
-
- // Go through the list until find the value or the end
- while ((node) && (node->getValue() != value))
- {
- node = node->next;
- }
- // Throw exception if didn't find the value
- if (!node)
- {
- throw std::logic_error("Value must be in the list!");
- }
-
- // Remove all pointier to the value if exists
- this->remove_pointers_to(node);
-
- // Delete node
- delete (node);
- }
-
- // Removes the k-th element, where k it's an ordinal number
- void remove_ordinary(int position)
- {
- if (this->isEmpty())
- {
- throw std::logic_error("List is empty, nothing to be removed!");
- }
-
- if (position < 1)
- {
- throw std::logic_error("Invalid position!");
- }
-
- Node *selectedNode = this->first;
- int aux = 1;
-
- while ((selectedNode) && (aux != position))
- {
- selectedNode = selectedNode->next;
- aux++;
- }
-
- if (!selectedNode)
- {
- throw std::logic_error("Index out of bound!");
- }
-
- this->remove_pointers_to(selectedNode);
-
- delete (selectedNode);
- }
-
- std::pair find(int value)
- {
- // Throw exception to empty List
- if (this->isEmpty())
- {
- throw std::logic_error("List is empty, nothing to be removed!");
- }
-
- // Initialize a pointier to first element
- Node *node = this->first;
-
- // Go through the list until find the value or the end
- while ((node) && (node->getValue() != value))
- {
- node = node->next;
- }
-
- if (!node)
- {
- return {false, nullptr};
- }
- return {true, node};
- }
-
- void print()
- {
- Node *selectedNode = this->first;
- std::cout << "[ ";
- while (selectedNode)
- {
- std::cout << selectedNode->getValue() << " ";
- selectedNode = selectedNode->next;
- }
- std::cout << "]" << std::endl;
+ DoublyLinkedList() {}
+
+ void push_front(int value) {
+ // Initialize a pointier to a new node with received value
+ Node *node = new Node(value);
+ // Node points to the first
+ node->next = this->first;
+
+ // If there is a first node, make him point to new node
+ if (this->first) {
+ this->first->previous = node;
+ }
+
+ // Node becomes the first
+ this->first = node;
+ }
+
+ // Checks if there is a first node
+ bool isEmpty() {
+ if (!this->first) {
+ return true;
+ }
+ return false;
+ }
+
+ void push_back(int value) {
+ Node *node = new Node(value);
+ Node *selectedNode = this->first;
+
+ if (this->isEmpty()) {
+ this->first = node;
+ return;
+ }
+
+ Node *aux{nullptr};
+ while (selectedNode) {
+ aux = selectedNode;
+ selectedNode = selectedNode->next;
+ }
+
+ node->previous = aux;
+ aux->next = node;
+ };
+
+ void remove(int value) {
+ // Throw exception to empty List
+ if (this->isEmpty()) {
+ throw std::logic_error("List is empty, nothing to be removed!");
+ }
+
+ // Initialize a pointier to first element
+ Node *node = this->first;
+
+ // Go through the list until find the value or the end
+ while ((node) && (node->getValue() != value)) {
+ node = node->next;
+ }
+ // Throw exception if didn't find the value
+ if (!node) {
+ throw std::logic_error("Value must be in the list!");
+ }
+
+ // Remove all pointier to the value if exists
+ this->remove_pointers_to(node);
+
+ // Delete node
+ delete (node);
+ }
+
+ // Removes the k-th element, where k it's an ordinal number
+ void remove_ordinary(int position) {
+ if (this->isEmpty()) {
+ throw std::logic_error("List is empty, nothing to be removed!");
+ }
+
+ if (position < 1) {
+ throw std::logic_error("Invalid position!");
+ }
+
+ Node *selectedNode = this->first;
+ int aux = 1;
+
+ while ((selectedNode) && (aux != position)) {
+ selectedNode = selectedNode->next;
+ aux++;
+ }
+
+ if (!selectedNode) {
+ throw std::logic_error("Index out of bound!");
+ }
+
+ this->remove_pointers_to(selectedNode);
+
+ delete (selectedNode);
+ }
+
+ std::pair find(int value) {
+ // Throw exception to empty List
+ if (this->isEmpty()) {
+ throw std::logic_error("List is empty, nothing to be removed!");
+ }
+
+ // Initialize a pointier to first element
+ Node *node = this->first;
+
+ // Go through the list until find the value or the end
+ while ((node) && (node->getValue() != value)) {
+ node = node->next;
+ }
+
+ if (!node) {
+ return {false, nullptr};
+ }
+ return {true, node};
+ }
+
+ void print() {
+ Node *selectedNode = this->first;
+ std::cout << "[ ";
+ while (selectedNode) {
+ std::cout << selectedNode->getValue() << " ";
+ selectedNode = selectedNode->next;
}
+ std::cout << "]" << std::endl;
+ }
};
-int main()
-{
- DoublyLinkedList *doubly_linked_list = new DoublyLinkedList();
+int main() {
+ DoublyLinkedList *doubly_linked_list = new DoublyLinkedList();
- std::cout << "Push_front(20, 30, 40):" << std::endl;
- doubly_linked_list->push_front(20);
- doubly_linked_list->push_front(30);
- doubly_linked_list->push_front(40);
+ std::cout << "Push_front(20, 30, 40):" << std::endl;
+ doubly_linked_list->push_front(20);
+ doubly_linked_list->push_front(30);
+ doubly_linked_list->push_front(40);
- doubly_linked_list->print();
+ doubly_linked_list->print();
- std::cout << "Remove second!" << std::endl;
+ std::cout << "Remove second!" << std::endl;
- doubly_linked_list->remove_ordinary(2);
+ doubly_linked_list->remove_ordinary(2);
- doubly_linked_list->print();
+ doubly_linked_list->print();
- std::cout << "Remove(20, 40)!" << std::endl;
- doubly_linked_list->remove(20);
- doubly_linked_list->remove(40);
+ std::cout << "Remove(20, 40)!" << std::endl;
+ doubly_linked_list->remove(20);
+ doubly_linked_list->remove(40);
- std::cout << "List is empty: ";
- doubly_linked_list->print();
+ std::cout << "List is empty: ";
+ doubly_linked_list->print();
- std::cout << "Push_back(512, 123, 412)!" << std::endl;
- doubly_linked_list->push_back(512);
- doubly_linked_list->push_back(123);
- doubly_linked_list->push_back(412);
+ std::cout << "Push_back(512, 123, 412)!" << std::endl;
+ doubly_linked_list->push_back(512);
+ doubly_linked_list->push_back(123);
+ doubly_linked_list->push_back(412);
- doubly_linked_list->print();
+ doubly_linked_list->print();
}
diff --git a/src/cpp/DynamicQueue.cpp b/src/cpp/DynamicQueue.cpp
index b0ad8c58..55da0122 100644
--- a/src/cpp/DynamicQueue.cpp
+++ b/src/cpp/DynamicQueue.cpp
@@ -9,11 +9,11 @@ struct Node {
};
class DynamicQueue {
- private:
+private:
Node *_begin;
Node *_end;
- public:
+public:
DynamicQueue() : _begin(nullptr), _end(nullptr) {}
~DynamicQueue() {
@@ -83,11 +83,11 @@ int main(void) {
queue.enqueue(5);
queue.enqueue(1231);
queue.enqueue(515);
- queue.print(); // 42 5 1231 515
+ queue.print(); // 42 5 1231 515
// Use 'delete' keyword to make the code leak-free
queue.dequeue();
queue.dequeue();
- queue.print(); // 1231 515
+ queue.print(); // 1231 515
return 0;
}
diff --git a/src/cpp/DynamicStack.cpp b/src/cpp/DynamicStack.cpp
index 0be4e546..08e11178 100644
--- a/src/cpp/DynamicStack.cpp
+++ b/src/cpp/DynamicStack.cpp
@@ -23,9 +23,7 @@ class Stack {
head = newNode;
}
- bool isEmpty() {
- return head == nullptr;
- }
+ bool isEmpty() { return head == nullptr; }
int pop() {
int value = emptyStack;
diff --git a/src/cpp/Exponentiation.cpp b/src/cpp/Exponentiation.cpp
index b5f07bc4..1e01d9ba 100644
--- a/src/cpp/Exponentiation.cpp
+++ b/src/cpp/Exponentiation.cpp
@@ -1,20 +1,18 @@
#include
-
int main() {
- long long int n, exp;
+ long long int n, exp;
- std::cin >> n >> exp;
+ std::cin >> n >> exp;
- long long int result = 1;
+ long long int result = 1;
- for (long long int i = 0; i < exp; i++) {
- result *= n;
- }
+ for (long long int i = 0; i < exp; i++) {
+ result *= n;
+ }
- std::cout << result << std::endl;
-
+ std::cout << result << std::endl;
- return 0;
+ return 0;
}
diff --git a/src/cpp/ExponentiationRecursive.cpp b/src/cpp/ExponentiationRecursive.cpp
index 5b2f1c42..a8fd83fb 100644
--- a/src/cpp/ExponentiationRecursive.cpp
+++ b/src/cpp/ExponentiationRecursive.cpp
@@ -2,22 +2,20 @@
long long int exp(int n, int pow) {
- if(pow == 0)
- return 1;
+ if (pow == 0)
+ return 1;
- return n * exp(n, pow-1);
+ return n * exp(n, pow - 1);
}
-
int main() {
- long long int n, pow;
+ long long int n, pow;
- std::cin >> n >> pow;
+ std::cin >> n >> pow;
- n = exp(n, pow);
- std::cout << n << std::endl;
-
+ n = exp(n, pow);
+ std::cout << n << std::endl;
- return 0;
+ return 0;
}
diff --git a/src/cpp/Factorial.cpp b/src/cpp/Factorial.cpp
index e6eaa18c..4c082b3c 100644
--- a/src/cpp/Factorial.cpp
+++ b/src/cpp/Factorial.cpp
@@ -2,21 +2,21 @@
int factorial(int n) {
- int fact = 1;
- for (size_t i = 1; i <= n; i++) {
- fact = i*fact;
- }
+ int fact = 1;
+ for (size_t i = 1; i <= n; i++) {
+ fact = i * fact;
+ }
- return fact;
+ return fact;
}
int main() {
- int nums[] = {0, 1, 2, 3, 4, 5};
+ int nums[] = {0, 1, 2, 3, 4, 5};
- for(auto i : nums) {
- std::cout << std::to_string(i)+"! = " << factorial(i) << std::endl;
- }
+ for (auto i : nums) {
+ std::cout << std::to_string(i) + "! = " << factorial(i) << std::endl;
+ }
- return 0;
+ return 0;
}
diff --git a/src/cpp/FactorialRecursive.cpp b/src/cpp/FactorialRecursive.cpp
index e222a2e4..2d584c65 100644
--- a/src/cpp/FactorialRecursive.cpp
+++ b/src/cpp/FactorialRecursive.cpp
@@ -2,21 +2,20 @@
int factorial(int n) {
- if(n == 0)
- return 1;
-
- else
- return n * (factorial(n-1));
+ if (n == 0)
+ return 1;
+ else
+ return n * (factorial(n - 1));
}
int main() {
- int nums[] = {0, 1, 2, 3, 4, 5};
+ int nums[] = {0, 1, 2, 3, 4, 5};
- for(auto i : nums) {
- std::cout << std::to_string(i)+"! = " << factorial(i) << std::endl;
- }
+ for (auto i : nums) {
+ std::cout << std::to_string(i) + "! = " << factorial(i) << std::endl;
+ }
- return 0;
+ return 0;
}
diff --git a/src/cpp/FibonacciIterative.cpp b/src/cpp/FibonacciIterative.cpp
index 5fbab951..3f5e04f8 100644
--- a/src/cpp/FibonacciIterative.cpp
+++ b/src/cpp/FibonacciIterative.cpp
@@ -3,16 +3,14 @@
using namespace std;
int fibonacci(int n) {
- int last = 0;
- int curr = 1;
- for (int index = 0; index < n; ++index) {
- int temp = curr;
- curr += last;
- last = temp;
- }
- return last;
+ int last = 0;
+ int curr = 1;
+ for (int index = 0; index < n; ++index) {
+ int temp = curr;
+ curr += last;
+ last = temp;
+ }
+ return last;
}
-int main() {
- cout << fibonacci(12) << endl;
-}
+int main() { cout << fibonacci(12) << endl; }
diff --git a/src/cpp/FibonacciMemoization.cpp b/src/cpp/FibonacciMemoization.cpp
index 9b8a6e91..0d133f65 100644
--- a/src/cpp/FibonacciMemoization.cpp
+++ b/src/cpp/FibonacciMemoization.cpp
@@ -6,23 +6,23 @@ using namespace std;
vector memo;
int fibonacci(int n) {
- if (n <= 1) {
- return n;
- }
- if (memo[n] != -1) {
- return memo[n];
- }
-
- memo[n] = fibonacci(n - 1) + fibonacci(n - 2);
+ if (n <= 1) {
+ return n;
+ }
+ if (memo[n] != -1) {
return memo[n];
+ }
+
+ memo[n] = fibonacci(n - 1) + fibonacci(n - 2);
+ return memo[n];
}
int main() {
- int test_nbr = 12;
+ int test_nbr = 12;
- // Initialize the memoization table with -1 (uncomputed)
- memo.assign(test_nbr + 1, -1);
+ // Initialize the memoization table with -1 (uncomputed)
+ memo.assign(test_nbr + 1, -1);
- cout << "memoization: " << fibonacci(test_nbr) << endl;
- return 0;
+ cout << "memoization: " << fibonacci(test_nbr) << endl;
+ return 0;
}
diff --git a/src/cpp/FibonacciRecursive.cpp b/src/cpp/FibonacciRecursive.cpp
index b740c642..703ad130 100644
--- a/src/cpp/FibonacciRecursive.cpp
+++ b/src/cpp/FibonacciRecursive.cpp
@@ -3,12 +3,10 @@
using namespace std;
int fibonacci(int n) {
- if (n <= 1) {
- return n;
- }
- return fibonacci(n-1) + fibonacci(n-2);
+ if (n <= 1) {
+ return n;
+ }
+ return fibonacci(n - 1) + fibonacci(n - 2);
}
-int main() {
- cout << fibonacci(12) << endl;
-}
+int main() { cout << fibonacci(12) << endl; }
diff --git a/src/cpp/FindDistinctSubsets.cpp b/src/cpp/FindDistinctSubsets.cpp
index 48699329..c0af7813 100644
--- a/src/cpp/FindDistinctSubsets.cpp
+++ b/src/cpp/FindDistinctSubsets.cpp
@@ -7,7 +7,8 @@ Problem Statement:
Given an integer array nums of unique elements, return all possible
subsets (the power set).
-The solution set must not contain duplicate subsets. Return the solution in any order.
+The solution set must not contain duplicate subsets. Return the solution in any
+order.
*/
// Using Bit Manipulation
@@ -19,44 +20,39 @@ The solution set must not contain duplicate subsets. Return the solution in any
// where 1 means that element is present in the subset
// Time: O(n * 2ⁿ)
// Space: O(1)
-vector> subsets(vector &nums)
-{
- int n = nums.size();
- int total = 1 << n; // 2ⁿ
- vector> ans(total);
-
- // Traverse all subsets
- for (int i = 0; i < total; i++) // 2ⁿ
+vector> subsets(vector &nums) {
+ int n = nums.size();
+ int total = 1 << n; // 2ⁿ
+ vector> ans(total);
+
+ // Traverse all subsets
+ for (int i = 0; i < total; i++) // 2ⁿ
+ {
+ // Traverse elements of nums
+ for (int j = 0; j < n; j++) // n
{
- // Traverse elements of nums
- for (int j = 0; j < n; j++) // n
- {
- // Check if jth bit is set in i
- if ((1 << j) & i)
- {
- ans[i].push_back(nums[j]);
- }
- }
+ // Check if jth bit is set in i
+ if ((1 << j) & i) {
+ ans[i].push_back(nums[j]);
+ }
}
+ }
- return ans;
+ return ans;
}
-int main()
-{
- vector nums = {1, 2, 3};
- vector> ans = subsets(nums);
+int main() {
+ vector nums = {1, 2, 3};
+ vector> ans = subsets(nums);
- cout << "Subsets are: \n";
- for (auto v : ans)
- {
- cout << "[ ";
- for (auto i : v)
- {
- cout << i << " ";
- }
- cout << "]\n";
+ cout << "Subsets are: \n";
+ for (auto v : ans) {
+ cout << "[ ";
+ for (auto i : v) {
+ cout << i << " ";
}
+ cout << "]\n";
+ }
- return 0;
+ return 0;
}
diff --git a/src/cpp/FloydWarshall.cpp b/src/cpp/FloydWarshall.cpp
new file mode 100644
index 00000000..3a6e53d2
--- /dev/null
+++ b/src/cpp/FloydWarshall.cpp
@@ -0,0 +1,67 @@
+#include
+
+using namespace std;
+
+// Function to display the matrix
+void showMatrix(const vector> &matrix, int numVertices) {
+ for (int i = 0; i < numVertices; i++) {
+ for (int j = 0; j < numVertices; j++) {
+ if (matrix[i][j] < 10) // For better alignment
+ cout << " ";
+ cout << matrix[i][j] << " ";
+ }
+ cout << endl;
+ }
+ cout << endl;
+}
+
+// Floyd-Warshall algorithm
+void floydWarshall(vector> &matrix, int n) {
+ for (int k = 0; k < n; k++) // Intermediary vertex
+ {
+ for (int i = 0; i < n; i++) // Origin vertex
+ {
+ for (int j = 0; j < n; j++) // Destination vertex
+ {
+ if (matrix[i][k] != LONG_MAX && // i -> k exists
+ matrix[k][j] != LONG_MAX && // k -> j exists
+ matrix[i][j] >
+ matrix[i][k] + matrix[k][j]) // i -> j is shorter via k
+ {
+ matrix[i][j] = matrix[i][k] + matrix[k][j]; // Update i -> j
+ }
+ }
+ }
+ }
+}
+
+int main() {
+ int numVertices = 5;
+
+ // Initialize matrix with given values
+ vector> matrix = {{0, 2, 10, 5, 7},
+ {2, 0, 3, 3, 1},
+ {10, 3, 0, 1, 2},
+ {5, 3, 1, 0, LONG_MAX},
+ {7, 1, 2, 2, 0}};
+
+ // Display the original matrix
+ cout << "Original matrix:" << endl;
+ showMatrix(matrix, numVertices);
+
+ // Apply Floyd-Warshall algorithm
+ floydWarshall(matrix, numVertices);
+
+ // Display the updated matrix
+ cout << "Updated matrix:" << endl;
+ showMatrix(matrix, numVertices);
+
+ // Show all shortest paths in 3 columns: source, destination, shortest
+ // distance
+ cout << "Source\tDestination\tShortest Distance" << endl;
+ for (int i = 0; i < numVertices; i++)
+ for (int j = 0; j < numVertices; j++)
+ cout << i << "\t" << j << "\t\t" << matrix[i][j] << endl;
+
+ return 0;
+}
diff --git a/src/cpp/GraphSearch.cpp b/src/cpp/GraphSearch.cpp
new file mode 100644
index 00000000..aa2aea1c
--- /dev/null
+++ b/src/cpp/GraphSearch.cpp
@@ -0,0 +1,121 @@
+#include
+#include
+#include
+
+#define MAX_VERTICES 6 // Maximum number of vertices in the graph
+
+// Structure that defines each Vertex of the Graph
+struct Vertex {
+ char id;
+ std::vector neighbors; // List of neighbors
+ bool visited;
+
+ Vertex(char id) : id(id), visited(false) {}
+};
+
+// Creates a vertex and returns it
+Vertex *createVertex(char id) { return new Vertex(id); }
+
+// Links two vertices (makes them neighbors)
+void linkVertices(Vertex *v1, Vertex *v2) {
+ v1->neighbors.push_back(v2); // Add v2 as a neighbor of v1
+ v2->neighbors.push_back(v1); // Add v1 as a neighbor of v2
+}
+
+/*
+ * Depth First Search (DFS)
+ * Recursively visits neighbors of the starting vertex
+ */
+int depthFirstSearch(Vertex *start, Vertex *destination, int steps) {
+ start->visited = true; // Mark the current vertex as visited
+ if (start == destination)
+ return steps; // If found, return the distance
+
+ for (Vertex *neighbor : start->neighbors) { // Visit all neighbors
+ if (!neighbor->visited) { // If neighbor hasn't been visited
+ int result = depthFirstSearch(neighbor, destination, steps + 1);
+ if (result != -1)
+ return result; // If destination found, return result
+ }
+ }
+ return -1; // Destination not found
+}
+
+/*
+ * Breadth First Search (BFS)
+ * Uses a queue to traverse level by level
+ */
+int breadthFirstSearch(Vertex *start, Vertex *destination) {
+ std::queue q;
+ q.push(start); // Enqueue starting vertex
+ start->visited = true;
+
+ int steps = 0;
+
+ while (!q.empty()) {
+ int qSize = q.size(); // Current queue size (level size)
+
+ // Process all vertices at the current level
+ for (int i = 0; i < qSize; i++) {
+ Vertex *current = q.front();
+ q.pop();
+
+ if (current == destination)
+ return steps; // If destination found, return steps
+
+ // Enqueue all unvisited neighbors
+ for (Vertex *neighbor : current->neighbors) {
+ if (!neighbor->visited) {
+ neighbor->visited = true;
+ q.push(neighbor);
+ }
+ }
+ }
+ steps++; // Increment the level
+ }
+ return -1; // Destination not found
+}
+
+int main() {
+ // Create vertices
+ Vertex *A = createVertex('A');
+ Vertex *B = createVertex('B');
+ Vertex *C = createVertex('C');
+ Vertex *D = createVertex('D');
+ Vertex *E = createVertex('E');
+ Vertex *F = createVertex('F');
+
+ // Link vertices as per the graph structure
+ linkVertices(A, B);
+ linkVertices(A, C);
+ linkVertices(B, D);
+ linkVertices(C, D);
+ linkVertices(B, E);
+ linkVertices(D, E);
+ linkVertices(E, F);
+ linkVertices(D, F);
+
+ // Perform Depth First Search
+ int result = depthFirstSearch(A, F, 0);
+ if (result != -1)
+ std::cout << "DFS - Found. Distance: " << result << std::endl;
+ else
+ std::cout << "DFS - Not Found." << std::endl;
+
+ // Reset visited status for all vertices
+ A->visited = false;
+ B->visited = false;
+ C->visited = false;
+ D->visited = false;
+ E->visited = false;
+ F->visited = false;
+
+ // Perform Breadth First Search
+ result = breadthFirstSearch(A, F);
+ if (result != -1)
+ std::cout << "BFS - Found. Distance: " << result << std::endl;
+ else
+ std::cout << "BFS - Not Found." << std::endl;
+
+ return 0;
+}
diff --git a/src/cpp/InsertionSort.cpp b/src/cpp/InsertionSort.cpp
index 566d659c..72a80c1a 100644
--- a/src/cpp/InsertionSort.cpp
+++ b/src/cpp/InsertionSort.cpp
@@ -5,38 +5,32 @@ using namespace std;
void insertionSort(vector &vector) {
- for (uint32_t index = 1; index < vector.size(); index++)
- {
- int key = vector[index];
- int i = index - 1;
-
- while (i >= 0 && vector[i] > key)
- {
- vector[i+1] = vector[i];
- i--;
- }
-
- vector[i+1] = key;
- }
-}
+ for (uint32_t index = 1; index < vector.size(); index++) {
+ int key = vector[index];
+ int i = index - 1;
-void showVector(vector vector)
-{
- for (uint32_t i = 0; i < vector.size(); ++i)
- {
- cout << vector[i] << ", ";
+ while (i >= 0 && vector[i] > key) {
+ vector[i + 1] = vector[i];
+ i--;
}
- cout << "\n";
+
+ vector[i + 1] = key;
+ }
}
-int main()
-{
- vector vector;
- for (uint32_t i = 0; i < 10; ++i)
- {
- vector.push_back(rand() % 100);
- }
- showVector(vector);
- insertionSort(vector);
- showVector(vector);
+void showVector(vector vector) {
+ for (uint32_t i = 0; i < vector.size(); ++i) {
+ cout << vector[i] << ", ";
+ }
+ cout << "\n";
+}
+
+int main() {
+ vector vector;
+ for (uint32_t i = 0; i < 10; ++i) {
+ vector.push_back(rand() % 100);
+ }
+ showVector(vector);
+ insertionSort(vector);
+ showVector(vector);
}
diff --git a/src/cpp/InterpolationSearch.cpp b/src/cpp/InterpolationSearch.cpp
index ae046db2..3026ffe7 100644
--- a/src/cpp/InterpolationSearch.cpp
+++ b/src/cpp/InterpolationSearch.cpp
@@ -1,65 +1,63 @@
-//Time Complexity: O(log(logn))
+// Time Complexity: O(log(logn))
-#include
-#include
+#include
+#include
using namespace std;
// If x is present in arr[0..n-1], then returns
// index of it, else returns -1.
-long long int interpolation_search(int arr[],int n,int x)
-{
- int low=0,high=n-1;
+long long int interpolation_search(int arr[], int n, int x) {
+ int low = 0, high = n - 1;
- //Beacuse the array is sorted, element has to be present in range
- //made by corner i.e low and high
+ // Beacuse the array is sorted, element has to be present in range
+ // made by corner i.e low and high
- while ((low<=high) and (x>=arr[low]) and (x<=arr[high]))
- {
- // Now we will enquire the position keeping in mind the uniform distribution in mind
- int pos=low+(((double)(high-low)/(arr[high]-arr[low]))*(x-arr[low]));
+ while ((low <= high) and (x >= arr[low]) and (x <= arr[high])) {
+ // Now we will enquire the position keeping in mind the uniform distribution
+ // in mind
+ int pos = low + (((double)(high - low) / (arr[high] - arr[low])) *
+ (x - arr[low]));
- // If x is larger, x is in upper part
- if (arr[pos]x)
- high=pos-1;
+ // If x is smaller, x is in lower part
+ else if (arr[pos] > x)
+ high = pos - 1;
- // Target found
- else
- return pos;
- }
- return -1;
+ // Target found
+ else
+ return pos;
+ }
+ return -1;
}
-int main()
-{
- int n;
- cout<<"Please enter the number of elements in array\n";
- cin>>n;
- int arr[n];
+int main() {
+ int n;
+ cout << "Please enter the number of elements in array\n";
+ cin >> n;
+ int arr[n];
- cout<<"Please enter "<>arr[i];
- }
+ cout << "Please enter " << n << " numbers for arrays\n";
+ for (int i = 0; i < n; i++) {
+ cin >> arr[i];
+ }
- // For Interpolation search we need to sort the array
- sort(arr,arr+n);
+ // For Interpolation search we need to sort the array
+ sort(arr, arr + n);
- cout<<"Enter the number you want to search\n";
- int x;// Target number
- cin>>x;
+ cout << "Enter the number you want to search\n";
+ int x; // Target number
+ cin >> x;
- int index=interpolation_search(arr, n, x);
+ int index = interpolation_search(arr, n, x);
- // If element was found
- if (index != -1)
- cout<<"Element found at index "< &nums, int target) {
- for (size_t i = 0; i < nums.size(); i++) {
-
- if(nums[i] == target)
- return i;
- }
-
- return -1;
+ for (size_t i = 0; i < nums.size(); i++) {
+
+ if (nums[i] == target)
+ return i;
+ }
+
+ return -1;
}
int main() {
- vector nums = {1, 2, 3, 4, 5, 27, -1, 12, 999};
- int target;
-
- cout << "Enter the number you would like to search in the vector: ";
- cin >> target;
- cout << "\n";
+ vector nums = {1, 2, 3, 4, 5, 27, -1, 12, 999};
+ int target;
+
+ cout << "Enter the number you would like to search in the vector: ";
+ cin >> target;
+ cout << "\n";
- int pos = linear_search(nums, target);
+ int pos = linear_search(nums, target);
- if(pos > -1) {
- cout << "Number found in the vector in the position: " << pos << endl;
- }
- else {
- cout << "Number not found in the vector." << endl;
- }
+ if (pos > -1) {
+ cout << "Number found in the vector in the position: " << pos << endl;
+ } else {
+ cout << "Number not found in the vector." << endl;
+ }
- return 0;
+ return 0;
}
\ No newline at end of file
diff --git a/src/cpp/LinearSearchRecursive.cpp b/src/cpp/LinearSearchRecursive.cpp
index 0d2c9281..6c0cfbce 100644
--- a/src/cpp/LinearSearchRecursive.cpp
+++ b/src/cpp/LinearSearchRecursive.cpp
@@ -6,7 +6,7 @@ int linearSearchRecursive(int arr[], int n, int index, int target) {
if (index >= n) {
return -1;
}
-
+
if (arr[index] == target) {
return index;
}
diff --git a/src/cpp/MaxRecursive.cpp b/src/cpp/MaxRecursive.cpp
index 4a55b915..19bc79f9 100644
--- a/src/cpp/MaxRecursive.cpp
+++ b/src/cpp/MaxRecursive.cpp
@@ -1,37 +1,36 @@
#include
#include
-
int max_recursive(std::vector nums, int n) {
- if(n == 1)
- return nums[0];
- else{
- int aux = max_recursive(nums, n-1);
-
- if(aux > nums[n-1])
- return aux;
-
- return nums[n-1];
- }
+ if (n == 1)
+ return nums[0];
+ else {
+ int aux = max_recursive(nums, n - 1);
+
+ if (aux > nums[n - 1])
+ return aux;
+
+ return nums[n - 1];
+ }
}
int main() {
- std::vector nums{1, 2, 3, 4, 32, 6, 7, 8, 9, 10};
+ std::vector nums{1, 2, 3, 4, 32, 6, 7, 8, 9, 10};
+
+ std::cout << "nums = {";
+ for (auto &i : nums) {
- std::cout << "nums = {";
- for(auto& i : nums) {
+ std::cout << i;
- std::cout << i;
-
- if(&i != &nums.back()) {
- std::cout << ",";
- }
+ if (&i != &nums.back()) {
+ std::cout << ",";
}
- std::cout << "}" << std::endl;
+ }
+ std::cout << "}" << std::endl;
- std::cout << "Max = " << max_recursive(nums, nums.size()) << std::endl;
+ std::cout << "Max = " << max_recursive(nums, nums.size()) << std::endl;
- return 0;
+ return 0;
}
diff --git a/src/cpp/MergeSort.cpp b/src/cpp/MergeSort.cpp
index 17a4c82f..84b0241e 100644
--- a/src/cpp/MergeSort.cpp
+++ b/src/cpp/MergeSort.cpp
@@ -12,55 +12,52 @@
* @param right The right index of the second sub-array
*/
-void merge(std::vector& arr, int left, int mid, int right) {
-
- int n1 = mid - left + 1; // size of the first sub-array.
- int n2 = right - mid; // size of the second sub-array.
-
- // create temporary arrays to hold the data
- std::vector leftSubarray(n1);
- std::vector rightSubarray(n2);
-
- // copy data to temporary arrays leftSubarray[] and rightSubarray[]
- for (int i = 0; i < n1; i++) {
- leftSubarray[i] = arr[left + i];
- }
- for (int j = 0; j < n2; j++) {
- rightSubarray[j] = arr[mid + 1 + j];
- }
-
- // merge the two sub-arrays back into the original array arr[]
- int i = 0, j = 0, k = left;
-
- while (i < n1 && j < n2) {
- if (leftSubarray[i] <= rightSubarray[j]) {
- arr[k] = leftSubarray[i];
- i++;
- }
- else {
- arr[k] = rightSubarray[j];
- j++;
- }
- k++;
- }
-
- // copy the remaining elements of leftSubarray[], if any
- while (i < n1) {
- arr[k] = leftSubarray[i];
- i++;
- k++;
- }
-
- // copy the remaining elements of rightSubarray[], if any
- while (j < n2) {
- arr[k] = rightSubarray[j];
- j++;
- k++;
+void merge(std::vector &arr, int left, int mid, int right) {
+
+ int n1 = mid - left + 1; // size of the first sub-array.
+ int n2 = right - mid; // size of the second sub-array.
+
+ // create temporary arrays to hold the data
+ std::vector leftSubarray(n1);
+ std::vector rightSubarray(n2);
+
+ // copy data to temporary arrays leftSubarray[] and rightSubarray[]
+ for (int i = 0; i < n1; i++) {
+ leftSubarray[i] = arr[left + i];
+ }
+ for (int j = 0; j < n2; j++) {
+ rightSubarray[j] = arr[mid + 1 + j];
+ }
+
+ // merge the two sub-arrays back into the original array arr[]
+ int i = 0, j = 0, k = left;
+
+ while (i < n1 && j < n2) {
+ if (leftSubarray[i] <= rightSubarray[j]) {
+ arr[k] = leftSubarray[i];
+ i++;
+ } else {
+ arr[k] = rightSubarray[j];
+ j++;
}
+ k++;
+ }
+
+ // copy the remaining elements of leftSubarray[], if any
+ while (i < n1) {
+ arr[k] = leftSubarray[i];
+ i++;
+ k++;
+ }
+
+ // copy the remaining elements of rightSubarray[], if any
+ while (j < n2) {
+ arr[k] = rightSubarray[j];
+ j++;
+ k++;
+ }
}
-
-
/**
* Merge Sort algorithm
*
@@ -69,39 +66,39 @@ void merge(std::vector& arr, int left, int mid, int right) {
* @param right The right index of the sub-array to be sorted
*/
-void mergeSort(std::vector& arr, int left, int right) {
- if (left < right) {
+void mergeSort(std::vector &arr, int left, int right) {
+ if (left < right) {
- int mid = left + (right - left) / 2; // calculate the middle index
+ int mid = left + (right - left) / 2; // calculate the middle index
- // sort the first and second halves
- mergeSort(arr, left, mid);
- mergeSort(arr, mid + 1, right);
+ // sort the first and second halves
+ mergeSort(arr, left, mid);
+ mergeSort(arr, mid + 1, right);
- // merge the sorted halves
- merge(arr, left, mid, right);
- }
+ // merge the sorted halves
+ merge(arr, left, mid, right);
+ }
}
int main() {
- std::vector arr = {12, 11, 13, 5, 6, 7, 9, 4, 10, 9, 11, 1, 11};
+ std::vector arr = {12, 11, 13, 5, 6, 7, 9, 4, 10, 9, 11, 1, 11};
- int arrSize = arr.size();
+ int arrSize = arr.size();
- std::cout << "Original array: ";
- for (int num : arr) {
- std::cout << num << " ";
- }
- std::cout << std::endl;
+ std::cout << "Original array: ";
+ for (int num : arr) {
+ std::cout << num << " ";
+ }
+ std::cout << std::endl;
- mergeSort(arr, 0, arrSize - 1);
+ mergeSort(arr, 0, arrSize - 1);
- std::cout << "Sorted array: ";
- for (int num : arr) {
- std::cout << num << " ";
- }
- std::cout << std::endl;
+ std::cout << "Sorted array: ";
+ for (int num : arr) {
+ std::cout << num << " ";
+ }
+ std::cout << std::endl;
- return 0;
+ return 0;
}
diff --git a/src/cpp/MinMaxDC.cpp b/src/cpp/MinMaxDC.cpp
index 2f4d6d3c..cdffb794 100644
--- a/src/cpp/MinMaxDC.cpp
+++ b/src/cpp/MinMaxDC.cpp
@@ -11,49 +11,50 @@
* @param max Reference to store the maximum element
*/
-void MinAndMax(const std::vector& arr, int left, int right, int& min, int& max) {
-
- // if there is only one element in the subarray, it is both the minimum and maximum
- if (left == right) {
- min = max = arr[left];
- return;
+void MinAndMax(const std::vector &arr, int left, int right, int &min,
+ int &max) {
+
+ // if there is only one element in the subarray, it is both the minimum and
+ // maximum
+ if (left == right) {
+ min = max = arr[left];
+ return;
+ }
+
+ // if there are two elements, compare and set min and max
+ if (right - left == 1) {
+ if (arr[left] < arr[right]) {
+ min = arr[left];
+ max = arr[right];
+ } else {
+ min = arr[right];
+ max = arr[left];
}
+ return;
+ }
- // if there are two elements, compare and set min and max
- if (right - left == 1) {
- if (arr[left] < arr[right]) {
- min = arr[left];
- max = arr[right];
- }
- else {
- min = arr[right];
- max = arr[left];
- }
- return;
- }
-
- // calculate the middle index of the sub-array
- int mid = (left + right) / 2;
- int leftMin, leftMax, rightMin, rightMax;
+ // calculate the middle index of the sub-array
+ int mid = (left + right) / 2;
+ int leftMin, leftMax, rightMin, rightMax;
- // recursively find min and max in the left and right sub-arrays
- MinAndMax(arr, left, mid, leftMin, leftMax);
- MinAndMax(arr, mid + 1, right, rightMin, rightMax);
+ // recursively find min and max in the left and right sub-arrays
+ MinAndMax(arr, left, mid, leftMin, leftMax);
+ MinAndMax(arr, mid + 1, right, rightMin, rightMax);
- // update the minimum and maximum values
- min = std::min(leftMin, rightMin);
- max = std::max(leftMax, rightMax);
+ // update the minimum and maximum values
+ min = std::min(leftMin, rightMin);
+ max = std::max(leftMax, rightMax);
}
int main() {
- std::vector arr = {10, 5, 20, 8, 15, 30, -12, 24};
- int min, max;
+ std::vector arr = {10, 5, 20, 8, 15, 30, -12, 24};
+ int min, max;
- MinAndMax(arr, 0, arr.size() - 1, min, max);
+ MinAndMax(arr, 0, arr.size() - 1, min, max);
- std::cout << "Minimum element: " << min << std::endl;
- std::cout << "Maximum element: " << max << std::endl;
+ std::cout << "Minimum element: " << min << std::endl;
+ std::cout << "Maximum element: " << max << std::endl;
- return 0;
+ return 0;
}
diff --git a/src/cpp/MinMaxIterative.cpp b/src/cpp/MinMaxIterative.cpp
index 65d0e5d0..ea48d7ca 100644
--- a/src/cpp/MinMaxIterative.cpp
+++ b/src/cpp/MinMaxIterative.cpp
@@ -4,17 +4,19 @@ using namespace std;
int main() {
- int arr[] = {1, 5, -20, 6, 15};
+ int arr[] = {1, 5, -20, 6, 15};
- int min = arr[0];
- int max = arr[0];
+ int min = arr[0];
+ int max = arr[0];
- for(auto& i : arr) {
- if(i < min) min = i;
- else if(i > max) max = i;
- }
+ for (auto &i : arr) {
+ if (i < min)
+ min = i;
+ else if (i > max)
+ max = i;
+ }
- cout << "Max = " + to_string(max) + "\nMin = " + to_string(min) << endl;
+ cout << "Max = " + to_string(max) + "\nMin = " + to_string(min) << endl;
- return 0;
+ return 0;
}
diff --git a/src/cpp/Palindrome.cpp b/src/cpp/Palindrome.cpp
index 7dafc0b6..c8dd36c6 100644
--- a/src/cpp/Palindrome.cpp
+++ b/src/cpp/Palindrome.cpp
@@ -1,7 +1,9 @@
/*
isPalindrome Algorithm in C++
-A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
+A phrase is a palindrome if, after converting all uppercase letters into
+lowercase letters and removing all non-alphanumeric characters, it reads the
+same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
*/
@@ -12,43 +14,42 @@ Given a string s, return true if it is a palindrome, or false otherwise.
using namespace std;
bool isPalindrome(string s) {
- // Step 1: Convert all characters to lowercase
- for (char& c : s) {
- c = std::tolower(c);
+ // Step 1: Convert all characters to lowercase
+ for (char &c : s) {
+ c = std::tolower(c);
+ }
+
+ // Step 2: Remove non-alphanumeric characters
+ std::string alphanumericStr;
+ for (char c : s) {
+ if (std::isalnum(c)) {
+ alphanumericStr.push_back(c);
}
+ }
- // Step 2: Remove non-alphanumeric characters
- std::string alphanumericStr;
- for (char c : s) {
- if (std::isalnum(c)) {
- alphanumericStr.push_back(c);
- }
- }
-
- // Step 3: Check if the resulting string is a palindrome
- int left = 0;
- int right = alphanumericStr.length() - 1;
+ // Step 3: Check if the resulting string is a palindrome
+ int left = 0;
+ int right = alphanumericStr.length() - 1;
- while (left < right) {
- if (alphanumericStr[left] != alphanumericStr[right]) {
- return false;
- }
- left++;
- right--;
+ while (left < right) {
+ if (alphanumericStr[left] != alphanumericStr[right]) {
+ return false;
}
- return true;
+ left++;
+ right--;
+ }
+ return true;
}
int main() {
- std::string input;
- std::cout << "Enter a string: ";
- std::getline (std::cin, input);
-
- if (isPalindrome(input)) {
- std::cout << "The string is a palindrome." << std::endl;
- }
- else {
- std::cout << "The string is not a palindrome." << std::endl;
- }
- return 0;
+ std::string input;
+ std::cout << "Enter a string: ";
+ std::getline(std::cin, input);
+
+ if (isPalindrome(input)) {
+ std::cout << "The string is a palindrome." << std::endl;
+ } else {
+ std::cout << "The string is not a palindrome." << std::endl;
+ }
+ return 0;
}
diff --git a/src/cpp/QuickSort.cpp b/src/cpp/QuickSort.cpp
index 75daf1a0..ee9d726b 100644
--- a/src/cpp/QuickSort.cpp
+++ b/src/cpp/QuickSort.cpp
@@ -3,63 +3,50 @@
using namespace std;
-int partition(vector &vector, int start, int end)
-{
- int pivot = vector[end];
- int index = start;
-
- for (int i = start; i < end; i++)
- {
- if (vector[i] < pivot)
- {
- int temp = vector[i];
- vector[i] = vector[index];
- vector[index] = temp;
- index++;
- }
+int partition(vector &vector, int start, int end) {
+ int pivot = vector[end];
+ int index = start;
+
+ for (int i = start; i < end; i++) {
+ if (vector[i] < pivot) {
+ int temp = vector[i];
+ vector[i] = vector[index];
+ vector[index] = temp;
+ index++;
}
+ }
- if (pivot <= vector[index])
- {
- vector[end] = vector[index];
- vector[index] = pivot;
- }
+ if (pivot <= vector[index]) {
+ vector[end] = vector[index];
+ vector[index] = pivot;
+ }
- return index;
+ return index;
}
-void quickSort(vector &vector, int start, int end)
-{
- if (start < end)
- {
- int pivot = partition(vector, start, end);
- quickSort(vector, start, pivot-1);
- quickSort(vector, pivot+1, end);
- }
+void quickSort(vector &vector, int start, int end) {
+ if (start < end) {
+ int pivot = partition(vector, start, end);
+ quickSort(vector, start, pivot - 1);
+ quickSort(vector, pivot + 1, end);
+ }
}
-void quickSort(vector &vector)
-{
- quickSort(vector, 0, vector.size()-1);
-}
+void quickSort(vector &vector) { quickSort(vector, 0, vector.size() - 1); }
-void showVector(vector vector)
-{
- for (uint32_t i = 0; i < vector.size(); ++i)
- {
- cout << vector[i] << ", ";
- }
- cout << "\n";
+void showVector(vector vector) {
+ for (uint32_t i = 0; i < vector.size(); ++i) {
+ cout << vector[i] << ", ";
+ }
+ cout << "\n";
}
-int main()
-{
- vector vector;
- for (uint32_t i = 0; i < 10; ++i)
- {
- vector.push_back(rand() % 100);
- }
- showVector(vector);
- quickSort(vector);
- showVector(vector);
+int main() {
+ vector vector;
+ for (uint32_t i = 0; i < 10; ++i) {
+ vector.push_back(rand() % 100);
+ }
+ showVector(vector);
+ quickSort(vector);
+ showVector(vector);
}
diff --git a/src/cpp/RottenOranges.cpp b/src/cpp/RottenOranges.cpp
index 4c639476..0ce17c90 100644
--- a/src/cpp/RottenOranges.cpp
+++ b/src/cpp/RottenOranges.cpp
@@ -19,85 +19,74 @@ If it's not possible, return -1.
// Approach: BFS
-bool isValid(int nx, int ny, int m, int n)
-{
- return (0 <= nx && nx < m) &&
- (0 <= ny && ny < n);
+bool isValid(int nx, int ny, int m, int n) {
+ return (0 <= nx && nx < m) && (0 <= ny && ny < n);
}
// Time: O(mn) x 4
// Space: O(mn)
-int orangesRotting(vector> &grid)
-{
- int m = grid.size();
- int n = grid[0].size();
+int orangesRotting(vector> &grid) {
+ int m = grid.size();
+ int n = grid[0].size();
+
+ int total = 0; // fresh + rotten oranges
+ int count = 0; // rotten oranges
+ int mins = 0; // minutes elapsed
+
+ queue> rotten; // {i, j}: position of rotten orange
+
+ // Count the fresh & rotten oranges, push rotten oranges into queue
+ for (int i = 0; i < m; i++) {
+ for (int j = 0; j < n; j++) {
+ if (grid[i][j] != 0) // Rotten or Fresh orange
+ total++;
+ if (grid[i][j] == 2) // Rotten
+ rotten.push({i, j}); // Push position of rotten orange
+ }
+ }
- int total = 0; // fresh + rotten oranges
- int count = 0; // rotten oranges
- int mins = 0; // minutes elapsed
+ int dx[] = {0, 0, -1, 1}; // 4-directions (x-axis)
+ int dy[] = {-1, 1, 0, 0}; // 4-directions (y-axis)
- queue> rotten; // {i, j}: position of rotten orange
+ while (!rotten.empty()) {
+ int size = rotten.size(); // rotten oranges in current minute
+ count += size; // add to total rotten oranges
- // Count the fresh & rotten oranges, push rotten oranges into queue
- for (int i = 0; i < m; i++)
+ while (size--) // Each rotten orange in current minute
{
- for (int j = 0; j < n; j++)
- {
- if (grid[i][j] != 0) // Rotten or Fresh orange
- total++;
- if (grid[i][j] == 2) // Rotten
- rotten.push({i, j}); // Push position of rotten orange
+ // Pop the front rotten orange
+ int x = rotten.front().first;
+ int y = rotten.front().second;
+ rotten.pop();
+
+ // Check for fresh oranges in 4-directions
+ for (int i = 0; i < 4; i++) {
+ // New coordinates
+ int nx = x + dx[i];
+ int ny = y + dy[i];
+
+ // Valid, fresh orange
+ if (isValid(nx, ny, m, n) && grid[nx][ny] == 1) {
+ grid[nx][ny] = 2; // make it rotten
+ rotten.push({nx, ny}); // push it into queue
}
+ }
}
- int dx[] = {0, 0, -1, 1}; // 4-directions (x-axis)
- int dy[] = {-1, 1, 0, 0}; // 4-directions (y-axis)
-
- while (!rotten.empty())
- {
- int size = rotten.size(); // rotten oranges in current minute
- count += size; // add to total rotten oranges
-
- while (size--) // Each rotten orange in current minute
- {
- // Pop the front rotten orange
- int x = rotten.front().first;
- int y = rotten.front().second;
- rotten.pop();
-
- // Check for fresh oranges in 4-directions
- for (int i = 0; i < 4; i++)
- {
- // New coordinates
- int nx = x + dx[i];
- int ny = y + dy[i];
-
- // Valid, fresh orange
- if (isValid(nx, ny, m, n) && grid[nx][ny] == 1)
- {
- grid[nx][ny] = 2; // make it rotten
- rotten.push({nx, ny}); // push it into queue
- }
- }
- }
-
- if (!rotten.empty()) // if there are more rotten oranges
- mins++;
- }
+ if (!rotten.empty()) // if there are more rotten oranges
+ mins++;
+ }
- if (total != count) // fresh oranges left
- return -1;
+ if (total != count) // fresh oranges left
+ return -1;
- return mins;
+ return mins;
}
-int main()
-{
- vector> grid = {{2, 1, 1},
- {1, 1, 0},
- {0, 1, 1}};
+int main() {
+ vector> grid = {{2, 1, 1}, {1, 1, 0}, {0, 1, 1}};
- cout << orangesRotting(grid) << endl; // 4
+ cout << orangesRotting(grid) << endl; // 4
- return 0;
+ return 0;
}
diff --git a/src/cpp/SelectionSort.cpp b/src/cpp/SelectionSort.cpp
index a84b33f4..abffa69c 100644
--- a/src/cpp/SelectionSort.cpp
+++ b/src/cpp/SelectionSort.cpp
@@ -3,46 +3,38 @@
using namespace std;
-void selectionSort(vector &vector)
-{
- for (uint32_t index = 0; index < vector.size()-1; index++)
- {
- uint32_t min = index;
-
- for (uint32_t tempIndex = index+1; tempIndex < vector.size(); ++tempIndex)
- {
- if( vector[tempIndex] < vector[min] )
- {
- min = tempIndex;
- }
- }
-
- if( min != index )
- {
- int temp = vector[index];
- vector[index] = vector[min];
- vector[min] = temp;
- }
+void selectionSort(vector &vector) {
+ for (uint32_t index = 0; index < vector.size() - 1; index++) {
+ uint32_t min = index;
+
+ for (uint32_t tempIndex = index + 1; tempIndex < vector.size();
+ ++tempIndex) {
+ if (vector[tempIndex] < vector[min]) {
+ min = tempIndex;
+ }
}
-}
-void showVector(vector vector)
-{
- for (uint32_t i = 0; i < vector.size(); ++i)
- {
- cout << vector[i] << ", ";
+ if (min != index) {
+ int temp = vector[index];
+ vector[index] = vector[min];
+ vector[min] = temp;
}
- cout << "\n";
+ }
}
-int main()
-{
- vector vector;
- for (uint32_t i = 0; i < 10; ++i)
- {
- vector.push_back(rand() % 100);
- }
- showVector(vector);
- selectionSort(vector);
- showVector(vector);
+void showVector(vector vector) {
+ for (uint32_t i = 0; i < vector.size(); ++i) {
+ cout << vector[i] << ", ";
+ }
+ cout << "\n";
+}
+
+int main() {
+ vector vector;
+ for (uint32_t i = 0; i < 10; ++i) {
+ vector.push_back(rand() % 100);
+ }
+ showVector(vector);
+ selectionSort(vector);
+ showVector(vector);
}
\ No newline at end of file
diff --git a/src/cpp/SinglyLinkedList.cpp b/src/cpp/SinglyLinkedList.cpp
index 3b35c20f..ac5fbc0b 100644
--- a/src/cpp/SinglyLinkedList.cpp
+++ b/src/cpp/SinglyLinkedList.cpp
@@ -2,172 +2,173 @@
using namespace std;
-struct Node{
+struct Node {
- int val;
- Node* next;
+ int val;
+ Node *next;
- Node(int val) : val(val), next(nullptr) {}
- Node(int val, Node *next) : val(val), next(next) {}
+ Node(int val) : val(val), next(nullptr) {}
+ Node(int val, Node *next) : val(val), next(next) {}
};
void print_list(Node *head) {
- auto aux = head;
+ auto aux = head;
- cout << '[';
- while(aux) {
+ cout << '[';
+ while (aux) {
- cout << aux->val;
+ cout << aux->val;
- if(aux->next) {
- cout << ", ";
- }
-
- aux = aux->next;
+ if (aux->next) {
+ cout << ", ";
}
- cout << ']' << endl;
+
+ aux = aux->next;
+ }
+ cout << ']' << endl;
}
void push_back(Node **head, int val) {
+ Node *newNode = new Node(val);
- Node *newNode = new Node(val);
-
- if(*head == nullptr) {
- *head = newNode;
- }
-
- else {
+ if (*head == nullptr) {
+ *head = newNode;
+ }
- auto aux = *head;
+ else {
- while(aux->next) {
- aux = aux->next;
- }
+ auto aux = *head;
- aux->next = newNode;
+ while (aux->next) {
+ aux = aux->next;
}
+
+ aux->next = newNode;
+ }
}
void push_front(Node **head, int val) {
- Node *newNode = new Node(val, *head);
+ Node *newNode = new Node(val, *head);
- *head = newNode;
+ *head = newNode;
}
void insert_in_position(Node **head, int val, int pos) {
- if(pos == 0) {
- push_front(head, val);
- return;
- }
+ if (pos == 0) {
+ push_front(head, val);
+ return;
+ }
- Node* newNode = new Node(val);
+ Node *newNode = new Node(val);
- auto prev = *head;
- auto curr = *head;
+ auto prev = *head;
+ auto curr = *head;
- while(curr->next && pos) {
- prev = curr;
- curr = curr->next;
- pos--;
- }
+ while (curr->next && pos) {
+ prev = curr;
+ curr = curr->next;
+ pos--;
+ }
- prev->next = newNode;
- newNode->next = curr;
+ prev->next = newNode;
+ newNode->next = curr;
}
void pop_back(Node **head) {
- if(*head == nullptr) {
- return;
- }
+ if (*head == nullptr) {
+ return;
+ }
- auto prev = *head;
- auto curr = prev->next;
+ auto prev = *head;
+ auto curr = prev->next;
- while(curr->next) {
- prev = prev->next;
- curr = curr->next;
- }
+ while (curr->next) {
+ prev = prev->next;
+ curr = curr->next;
+ }
- prev->next = nullptr;
+ prev->next = nullptr;
- delete(curr);
+ delete (curr);
}
void pop_front(Node **head) {
- if(*head == nullptr) {
- return;
- }
+ if (*head == nullptr) {
+ return;
+ }
- auto aux = *head;
+ auto aux = *head;
- *head = aux->next;
+ *head = aux->next;
- delete(aux);
+ delete (aux);
}
void remove_from_position(Node **head, int pos) {
- if(*head == nullptr) {
- return;
- }
+ if (*head == nullptr) {
+ return;
+ }
- if(pos == 0) {
- pop_front(head);
- return;
- }
+ if (pos == 0) {
+ pop_front(head);
+ return;
+ }
- auto prev = *head;
- auto curr = *head;
+ auto prev = *head;
+ auto curr = *head;
- while(curr->next && pos) {
- prev = curr;
- curr = curr->next;
- pos--;
- }
+ while (curr->next && pos) {
+ prev = curr;
+ curr = curr->next;
+ pos--;
+ }
- if(pos == 0) {
- prev->next = curr->next;
- delete(curr);
- }
+ if (pos == 0) {
+ prev->next = curr->next;
+ delete (curr);
+ }
}
int main() {
- Node *head = nullptr;
-
- cout << "Inserting the elements at the end [1, 2, 3]:" << endl;
- push_back(&head, 1);
- push_back(&head, 2);
- push_back(&head, 3);
- print_list(head);
-
- cout << "Inserting the elements at the beginning [0, -1, -2]:" << endl;
- push_front(&head, 0);
- push_front(&head, -1);
- push_front(&head, -2);
- print_list(head);
-
- cout << "Inserting in positions 3, 4, 5 the elements [997, 998, 999] respectively:" << endl;
- insert_in_position(&head, 997, 3);
- insert_in_position(&head, 998, 4);
- insert_in_position(&head, 999, 5);
- print_list(head);
-
- cout << "Removing last element:" << endl;
- pop_back(&head);
- print_list(head);
-
- cout << "Removing first element:" << endl;
- pop_front(&head);
- print_list(head);
-
- cout << "Removing element in position 2:" << endl;
- remove_from_position(&head, 2);
- print_list(head);
+ Node *head = nullptr;
+
+ cout << "Inserting the elements at the end [1, 2, 3]:" << endl;
+ push_back(&head, 1);
+ push_back(&head, 2);
+ push_back(&head, 3);
+ print_list(head);
+
+ cout << "Inserting the elements at the beginning [0, -1, -2]:" << endl;
+ push_front(&head, 0);
+ push_front(&head, -1);
+ push_front(&head, -2);
+ print_list(head);
+
+ cout << "Inserting in positions 3, 4, 5 the elements [997, 998, 999] "
+ "respectively:"
+ << endl;
+ insert_in_position(&head, 997, 3);
+ insert_in_position(&head, 998, 4);
+ insert_in_position(&head, 999, 5);
+ print_list(head);
+
+ cout << "Removing last element:" << endl;
+ pop_back(&head);
+ print_list(head);
+
+ cout << "Removing first element:" << endl;
+ pop_front(&head);
+ print_list(head);
+
+ cout << "Removing element in position 2:" << endl;
+ remove_from_position(&head, 2);
+ print_list(head);
}
diff --git a/src/cpp/Stack.cpp b/src/cpp/Stack.cpp
index c123b497..a22ed118 100644
--- a/src/cpp/Stack.cpp
+++ b/src/cpp/Stack.cpp
@@ -6,64 +6,64 @@
// Stack: Last In - First Out (LIFO)
class Stack {
- private:
- int array[MAX];
- int index = 0;
-
- public:
- Stack(){}
+private:
+ int array[MAX];
+ int index = 0;
- void push(int element) {
- if (this->index >= MAX) {
- throw std::logic_error("Stack is full!");
- }
- this->array[index] = element;
- index++;
+public:
+ Stack() {}
+
+ void push(int element) {
+ if (this->index >= MAX) {
+ throw std::logic_error("Stack is full!");
}
+ this->array[index] = element;
+ index++;
+ }
- bool isEmpty() {
- if (!this->index) {
- return true;
- }
- return false;
+ bool isEmpty() {
+ if (!this->index) {
+ return true;
}
+ return false;
+ }
- int pop() {
- if (this->isEmpty()) {
- throw std::logic_error("Stack is empty!");
- }
- index--;
- int value = this->array[this->index];
- this->array[this->index] = 0;
- return value;
+ int pop() {
+ if (this->isEmpty()) {
+ throw std::logic_error("Stack is empty!");
}
+ index--;
+ int value = this->array[this->index];
+ this->array[this->index] = 0;
+ return value;
+ }
- void print() {
- std::cout << "[ ";
- for (int i = 0; i < this->index; i++) {
- std::cout << this->array[i] << " ";
- }
- std::cout << "]" << std::endl;
+ void print() {
+ std::cout << "[ ";
+ for (int i = 0; i < this->index; i++) {
+ std::cout << this->array[i] << " ";
}
+ std::cout << "]" << std::endl;
+ }
};
int main() {
- // Create a pointier to a new Stack instance
- Stack* stack = new Stack();
+ // Create a pointier to a new Stack instance
+ Stack *stack = new Stack();
- std::cout << "Push(1, 2, 4)" << std::endl;
- stack->push(1);
- stack->push(2);
- stack->push(4);
- stack->print();
+ std::cout << "Push(1, 2, 4)" << std::endl;
+ stack->push(1);
+ stack->push(2);
+ stack->push(4);
+ stack->print();
- std::cout << "Pop()" << std::endl;
- stack->pop();
- stack->print();
+ std::cout << "Pop()" << std::endl;
+ stack->pop();
+ stack->print();
- stack->pop();
- stack->pop();
+ stack->pop();
+ stack->pop();
- std::cout << "Empty Stack" << std::endl;
- stack->print();
+ std::cout << "Empty Stack" << std::endl;
+ stack->print();
}
diff --git a/src/cpp/TowerOfHanoi.cpp b/src/cpp/TowerOfHanoi.cpp
index 34f71fbe..d44e0bd0 100644
--- a/src/cpp/TowerOfHanoi.cpp
+++ b/src/cpp/TowerOfHanoi.cpp
@@ -2,67 +2,67 @@
Recursive Towers of Hanoi Solution
Problem Description: (from wikipedia)
- The Tower of Hanoi is a mathematical game or puzzle consisting of three rods and a number of disks of various diameters,
- which can slide onto any rod.
+ The Tower of Hanoi is a mathematical game or puzzle consisting of three rods
+ and a number of disks of various diameters, which can slide onto any rod.
- The puzzle begins with the disks stacked on one rod in order of decreasing size, the smallest at the top,
- thus approximating a conical shape.
+ The puzzle begins with the disks stacked on one rod in order of decreasing
+ size, the smallest at the top, thus approximating a conical shape.
- The objective of the puzzle is to move the entire stack to the last rod, obeying the following rules:
+ The objective of the puzzle is to move the entire stack to the last rod,
+ obeying the following rules:
Only one disk may be moved at a time.
- Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty rod.
+ Each move consists of taking the upper disk from one of the stacks and
+ placing it on top of another stack or on an empty rod.
No disk may be placed on top of a disk that is smaller than it.
With 3 disks, the puzzle can be solved in 7 moves.
- The minimal number of moves required to solve a Tower of Hanoi puzzle is 2^n − 1, where n is the number of disks.
+ The minimal number of moves required to solve a Tower of Hanoi puzzle is 2^n
+ − 1, where n is the number of disks.
*/
#include
using std::cout;
-size_t solve_tower(int n, char first, char second, char third)
-{
+size_t solve_tower(int n, char first, char second, char third) {
- // recursive base case
- if (n == 1)
- {
- cout << "Move disk 1 from " << first << " to " << third << "\n";
- return 1;
- }
+ // recursive base case
+ if (n == 1) {
+ cout << "Move disk 1 from " << first << " to " << third << "\n";
+ return 1;
+ }
- // move n-1 disks from first to other using second as a placeholder
- size_t num_moves = solve_tower(n - 1, first, third, second);
+ // move n-1 disks from first to other using second as a placeholder
+ size_t num_moves = solve_tower(n - 1, first, third, second);
- // move the nth disk from first to second
- cout << "Move disk " << n << " from " << first << " to " << third << "\n";
+ // move the nth disk from first to second
+ cout << "Move disk " << n << " from " << first << " to " << third << "\n";
- // move the n-1 disks from third to second using first as an placeholder
- num_moves += solve_tower(n - 1, second, first, third);
+ // move the n-1 disks from third to second using first as an placeholder
+ num_moves += solve_tower(n - 1, second, first, third);
- // return the total moves plus 1
- return num_moves + 1;
+ // return the total moves plus 1
+ return num_moves + 1;
}
-int main()
-{
+int main() {
- // names of rods
- char a = 'A';
- char b = 'B';
- char c = 'C';
+ // names of rods
+ char a = 'A';
+ char b = 'B';
+ char c = 'C';
- // number of disks to move in puzzle
- size_t num_disk = 3;
+ // number of disks to move in puzzle
+ size_t num_disk = 3;
- // find the total number of moves needed to solve
- size_t num_moves = solve_tower(num_disk, a, b, c);
+ // find the total number of moves needed to solve
+ size_t num_moves = solve_tower(num_disk, a, b, c);
- // output result
- cout << "Total moves needed to solve: " << num_moves;
- return 0;
+ // output result
+ cout << "Total moves needed to solve: " << num_moves;
+ return 0;
}
diff --git a/src/go/bubble_sort.go b/src/go/bubble_sort.go
index 62374a95..f63bb007 100644
--- a/src/go/bubble_sort.go
+++ b/src/go/bubble_sort.go
@@ -2,34 +2,34 @@ package main
import "fmt"
-// Iterativo
-func BubbleSortIterativo(slice []int) {
- for indice1 := len(slice) - 1; indice1 > 0; indice1-- {
- for indice2 := 0; indice2 < indice1; indice2++ {
- if slice[indice2] > slice[indice2+1] {
- slice[indice2], slice[indice2+1] = slice[indice2+1], slice[indice2]
+// Iterative
+func BubbleSortIterative(slice []int) {
+ for index1 := len(slice) - 1; index1 > 0; index1-- {
+ for index2 := 0; index2 < index1; index2++ {
+ if slice[index2] > slice[index2+1] {
+ slice[index2], slice[index2+1] = slice[index2+1], slice[index2]
}
}
}
}
-// Recursivo
-func BubbleSortRecursivo(slice []int, tamanho int) {
- trocas := 0
- for indice := 0; indice < tamanho-1; indice++ {
- if slice[indice] > slice[indice+1] {
- slice[indice], slice[indice+1] = slice[indice+1], slice[indice]
- trocas++
+// Recursive
+func BubbleSortRecursive(slice []int, size int) {
+ swaps := 0
+ for index := 0; index < size-1; index++ {
+ if slice[index] > slice[index+1] {
+ slice[index], slice[index+1] = slice[index+1], slice[index]
+ swaps++
}
}
- if trocas != 0 {
- BubbleSortRecursivo(slice, tamanho-1)
+ if swaps != 0 {
+ BubbleSortRecursive(slice, size-1)
}
}
func main() {
slice := []int{5, 2, 1, 6, 9, 8, 7, 3, 4}
fmt.Println("Slice:", slice)
- BubbleSortIterativo(slice)
+ BubbleSortIterative(slice)
fmt.Println("BubbleSort:", slice)
}
diff --git a/src/go/cocktail_sort.go b/src/go/cocktail_sort.go
index b9ce9ad3..a9f4a920 100644
--- a/src/go/cocktail_sort.go
+++ b/src/go/cocktail_sort.go
@@ -5,12 +5,12 @@ import "fmt"
func CocktailSort(slice []int) {
swapped := true
- begining := 0
+ beginning := 0
ending := len(slice) - 1
- for begining < ending && swapped {
+ for beginning < ending && swapped {
- for index := begining; index < ending; index++ {
+ for index := beginning; index < ending; index++ {
if slice[index] > slice[index+1] {
slice[index], slice[index+1] = slice[index+1], slice[index]
swapped = true
@@ -21,7 +21,7 @@ func CocktailSort(slice []int) {
if swapped {
swapped = false
- for index := ending; index > begining; index-- {
+ for index := ending; index > beginning; index-- {
if slice[index] < slice[index-1] {
slice[index], slice[index-1] = slice[index-1], slice[index]
swapped = true
@@ -29,7 +29,7 @@ func CocktailSort(slice []int) {
}
}
- begining++
+ beginning++
}
}
diff --git a/src/go/dijkstra.go b/src/go/dijkstra.go
index 80cae011..8139253d 100644
--- a/src/go/dijkstra.go
+++ b/src/go/dijkstra.go
@@ -1,12 +1,12 @@
/*
-* Grafos - Algoritmo de Dijkstra em Go
-* Complexidade: Teta(n^2)
-* Implementação utilizando matriz de adjacências (matriz de distância)
+* Graphs - Dijkstra's Algorithm in Go
+* Complexity: Theta(n^2)
+* Implementation using adjacency matrix (distance matrix)
*
-* 1 para todos - Arestas de pesos não negativo - Algoritmo guloso
-* Encontra o caminho mais curto de um vértice (inicio) a outro (destino)
+* One to all - Non-negative weighted edges - Greedy algorithm
+* Finds the shortest path from one vertex (start) to another (destination)
*
-* Grafo com 5 vértices e 6 arestas
+* Graph with 5 vertices and 6 edges
*
* 6
* (0)-----------------(1)
@@ -19,7 +19,7 @@
* \ /
* -----(4)-----
*
-* Matriz de Distância
+* Distance Matrix
* 0 1 2 3 4
* 0 0 6 10 - -
* 1 6 0 - 2 -
@@ -27,10 +27,10 @@
* 3 - 2 1 0 8
* 4 - - 3 8 0
*
-* O objetivo é sair do ponto inicial (0) e chegar ao destino (4) pelo caminho mais curto
-* Resposta: (0)->(1)->(3)->(2)->(4) = 12
+* The goal is to start from the initial point (0) and reach the destination (4) by the shortest path
+* Answer: (0)->(1)->(3)->(2)->(4) = 12
*
-* link Go PlayGround: https://play.golang.org/p/HyWAcYJ3qXY
+* Go PlayGround link: https://play.golang.org/p/HyWAcYJ3qXY
*/
package main
@@ -39,43 +39,43 @@ import "fmt"
var nroVertices = 5
-type Matriz [][]int
+type Matrix [][]int
var maxInt = 4294967295
-// Algoritmo de Dijkstra recebe como parâmetro a matriz de distância e o número de vértices
-func Dijkstra(matriz Matriz, n int) {
- visitados := make([]bool, n) // Variável que guarda true para os vértices visitados
- // O valor 'i' do for abaixo não é utilizado, pois o for serve apenas para percorrer todo o número de colunas da matriz
- for i := 1; i < n; i++ { // Começa em 1 pois não precisa comparar o vértice com ele mesmo
+// Dijkstra's Algorithm takes the distance matrix and the number of vertices as parameters
+func Dijkstra(matrix Matrix, n int) {
+ visited := make([]bool, n) // Variable that stores true for visited vertices
+ // The 'i' value in the for loop below is not used, as the loop is only used to iterate over the number of columns in the matrix
+ for i := 1; i < n; i++ { // Starts at 1 because there is no need to compare the vertex with itself
- min := -1 // Variável que guarda a posição do menor valor, inicia em -1 pois é uma posição inválida
- minValor := maxInt // Variável que guarda o menor valor encontrado, inicia com 'infinito', assim, sempre na primeira passada o valor será menor que esta variável
+ min := -1 // Variable that stores the position of the smallest value, starts at -1 because it is an invalid position
+ minValue := maxInt // Variable that stores the smallest value found, starts with 'infinity', so in the first pass the value will be smaller than this variable
- // For que percorre todas as linhas na coluna [0]
+ // For loop that iterates over all rows in column [0]
for j := 1; j < n; j++ {
- // Se o vertice ainda não foi visitado e o valor for menor que o 'MinValor'
- if !visitados[j] && matriz[j][0] < minValor {
- min = j // Guarda a posição do menor
- minValor = matriz[j][0] // Guarda o menor valor
+ // If the vertex has not been visited yet and the value is smaller than 'minValue'
+ if !visited[j] && matrix[j][0] < minValue {
+ min = j // Stores the position of the smallest value
+ minValue = matrix[j][0] // Stores the smallest value
}
}
- visitados[min] = true // Marca o valor a posição do minimo como visitado
+ visited[min] = true // Marks the position of the minimum as visited
- // For de 1 até n
+ // For loop from 1 to n
for j := 1; j < n; j++ {
- // Se o valor da coluna [0] + o valor da coluna que está passando for menor que o valor da linha que está passando e coluna [0]
- // Atualiza a primeira coluna da matriz, que será utilizado para as próximas iterações
- if (matriz[min][0] + matriz[min][j]) < matriz[j][0] {
- matriz[j][0] = matriz[min][0] + matriz[min][j]
+ // If the value of column [0] + the value of the current column is smaller than the value of the current row and column [0]
+ // Updates the first column of the matrix, which will be used for the next iterations
+ if (matrix[min][0] + matrix[min][j]) < matrix[j][0] {
+ matrix[j][0] = matrix[min][0] + matrix[min][j]
}
}
}
}
func main() {
- matriz := Matriz{
+ matrix := Matrix{
{0, 6, 10, maxInt, maxInt},
{6, 0, maxInt, 2, maxInt},
{10, maxInt, 0, 1, 3},
@@ -83,12 +83,12 @@ func main() {
{maxInt, maxInt, 3, 8, 0},
}
- Dijkstra(matriz, nroVertices)
+ Dijkstra(matrix, nroVertices)
- fmt.Printf("Total caminho mais curto do vertice 0 ao 4: %v\n\n", matriz[4][0]) // Caminho total mais curto
+ fmt.Printf("Total shortest path from vertex 0 to 4: %v\n\n", matrix[4][0]) // Total shortest path
- // Da print na matriz com os valores atualizados
- fmt.Println("Matriz:")
+ // Prints the matrix with the updated values
+ fmt.Println("Matrix:")
fmt.Printf("- | |v0 |v1 |v2 |v3 |v4\n")
fmt.Println("_____________________________________________")
@@ -100,10 +100,10 @@ func main() {
fmt.Printf("v%v |", i)
}
- if matriz[i][j] == maxInt {
+ if matrix[i][j] == maxInt {
fmt.Printf(" |inf")
} else {
- fmt.Printf(" |%v", matriz[i][j])
+ fmt.Printf(" |%v", matrix[i][j])
}
}
fmt.Println()
diff --git a/src/go/exponentiation.go b/src/go/exponentiation.go
index f9d45448..774b891c 100644
--- a/src/go/exponentiation.go
+++ b/src/go/exponentiation.go
@@ -2,13 +2,13 @@ package main
import "fmt"
-func Exponenciacao(base int, expoente int) int {
- for index := 0; index < (expoente - 1); index++ {
- base *= expoente
+func Exponentiation(base int, exponent int) int {
+ for index := 0; index < (exponent - 1); index++ {
+ base *= exponent
}
return base
}
func main() {
- fmt.Println("Exponenciacao:", Exponenciacao(5, 5))
+ fmt.Println("Exponentiation:", Exponentiation(5, 5))
}
diff --git a/src/go/factorial.go b/src/go/factorial.go
index 8c9658bf..6dbf1dd5 100644
--- a/src/go/factorial.go
+++ b/src/go/factorial.go
@@ -2,13 +2,13 @@ package main
import "fmt"
-func Fatorial(value int) int {
+func Factorial(value int) int {
if value == 1 {
return 1
}
- return value * Fatorial(value-1)
+ return value * Factorial(value-1)
}
func main() {
- fmt.Println("Fatorial:", Fatorial(6))
+ fmt.Println("Factorial:", Factorial(6))
}
diff --git a/src/go/floyd_warshall.go b/src/go/floyd_warshall.go
index 312212b0..c4c91ffc 100644
--- a/src/go/floyd_warshall.go
+++ b/src/go/floyd_warshall.go
@@ -2,25 +2,25 @@ package main
import "fmt"
-// Grafos - Algoritmo de Floyd-Warshall em GO
-// link Go PlayGround: https://go.dev/play/p/tIRTHkNf7Fz
+// Graphs - Floyd-Warshall Algorithm in GO
+// Go PlayGround link: https://go.dev/play/p/tIRTHkNf7Fz
-// Algoritmo de Floyd-Warshall
+// Floyd-Warshall Algorithm
func FloydWarshall(graph [][]int) [][]int {
- // Inicializa a matriz de distancias
+ // Initialize the distance matrix
dist := make([][]int, len(graph))
for i := range dist {
dist[i] = make([]int, len(graph))
copy(dist[i], graph[i])
}
- // Percorre os vértices
+ // Traverse the vertices
for k := 0; k < len(graph); k++ {
- // Percorre as linhas
+ // Traverse the rows
for i := 0; i < len(graph); i++ {
- // Percorre as colunas
+ // Traverse the columns
for j := 0; j < len(graph); j++ {
- // Verifica se o caminho passando pelo vértice k é menor
+ // Check if the path passing through vertex k is shorter
if dist[i][k]+dist[k][j] < dist[i][j] {
dist[i][j] = dist[i][k] + dist[k][j]
}
diff --git a/src/go/min_max_recursive.go b/src/go/min_max_recursive.go
index 40f10094..586cff7d 100644
--- a/src/go/min_max_recursive.go
+++ b/src/go/min_max_recursive.go
@@ -2,14 +2,14 @@ package main
import "fmt"
-func MaximoDivisaoEConquista(vetor []int, inicio int, fim int) int {
- if inicio == fim {
- return vetor[inicio]
+func MaxDivideAndConquer(array []int, start int, end int) int {
+ if start == end {
+ return array[start]
}
- meio := (inicio + fim) / 2
- aux1 := MaximoDivisaoEConquista(vetor, inicio, meio)
- aux2 := MaximoDivisaoEConquista(vetor, meio+1, fim)
+ middle := (start + end) / 2
+ aux1 := MaxDivideAndConquer(array, start, middle)
+ aux2 := MaxDivideAndConquer(array, middle+1, end)
if aux1 > aux2 {
return aux1
@@ -18,22 +18,22 @@ func MaximoDivisaoEConquista(vetor []int, inicio int, fim int) int {
return aux2
}
-func MinimoMaximoRecursivo(vetor []int, minimo int, maximo int, indice int) {
- if vetor[indice] < minimo {
- minimo = vetor[indice]
+func RecursiveMinMax(array []int, min int, max int, index int) {
+ if array[index] < min {
+ min = array[index]
}
- if vetor[indice] > maximo {
- maximo = vetor[indice]
+ if array[index] > max {
+ max = array[index]
}
- if indice < len(vetor)-1 {
- MinimoMaximoRecursivo(vetor, minimo, maximo, indice+1)
+ if index < len(array)-1 {
+ RecursiveMinMax(array, min, max, index+1)
} else {
- fmt.Println("Minimo:", minimo)
- fmt.Println("Maximo:", maximo)
+ fmt.Println("Minimum:", min)
+ fmt.Println("Maximum:", max)
}
}
func main() {
slice := []int{2, 3, 9, 1, 6, 8, 5}
- MinimoMaximoRecursivo(slice, 999, 0, 0)
+ RecursiveMinMax(slice, 999, 0, 0)
}
diff --git a/src/go/sorted_linked_list.go b/src/go/sorted_linked_list.go
index c2e1b52d..bc1eefaa 100644
--- a/src/go/sorted_linked_list.go
+++ b/src/go/sorted_linked_list.go
@@ -1,9 +1,9 @@
/*
-* Listas - Lista linear ordenada
+* Lists - Ordered linear list
*
-* Implementação da lista sequencial cujos elementos estão ordenados
+* Implementation of a sequential list whose elements are ordered
*
-* link Go PlayGround: https://play.golang.org/p/J6Jbi2_FWJk
+* Go PlayGround link: https://play.golang.org/p/J6Jbi2_FWJk
*/
package main
@@ -12,141 +12,141 @@ import "fmt"
var maxSize = 50
-// Estrura que será guardada em cada posição da lista
-type Registro struct {
- valor int
- // Outros campos podem ser adicionados aqui
+// Structure that will be stored in each position of the list
+type Record struct {
+ value int
+ // Other fields can be added here
}
-// Estrutura que guarda um arranjo de Registro, e o número de elementos no arranjo
-type Lista struct {
- arranjoRegistros []Registro
- numeroElementos int
+// Structure that holds an array of Records and the number of elements in the array
+type List struct {
+ recordArray []Record
+ numberOfElements int
}
-// Cria uma nova lista
-func criarLista() Lista {
- lista := Lista{
- arranjoRegistros: make([]Registro, maxSize),
- numeroElementos: 0,
+// Creates a new list
+func createList() List {
+ list := List{
+ recordArray: make([]Record, maxSize),
+ numberOfElements: 0,
}
- return lista
+ return list
}
-// reseta o contador de elementos da lista
-func inicializar(lista *Lista) {
- lista.numeroElementos = 0
+// Resets the list's element counter
+func initialize(list *List) {
+ list.numberOfElements = 0
}
-// Recupera a quantidade de elementos da lista
-func tamanho(lista *Lista) int {
- return lista.numeroElementos
+// Retrieves the number of elements in the list
+func size(list *List) int {
+ return list.numberOfElements
}
-// Imprime valores dos elementos na lista
-func imprimir(lista *Lista) {
- for i := 0; i < lista.numeroElementos; i++ {
- fmt.Printf("%v ", lista.arranjoRegistros[i].valor)
+// Prints the values of the elements in the list
+func show(list *List) {
+ for i := 0; i < list.numberOfElements; i++ {
+ fmt.Printf("%v ", list.recordArray[i].value)
}
fmt.Println()
}
-// Realiza busca binária na lista
-func buscaBinaria(lista *Lista, valor int) int {
- esquerda := 0
- direita := lista.numeroElementos - 1
+// Performs binary search on the list
+func binarySearch(list *List, value int) int {
+ left := 0
+ right := list.numberOfElements - 1
- for esquerda <= direita {
- meio := ((esquerda + direita) / 2)
- if lista.arranjoRegistros[meio].valor == valor {
- return meio
+ for left <= right {
+ middle := ((left + right) / 2)
+ if list.recordArray[middle].value == value {
+ return middle
}
- if lista.arranjoRegistros[meio].valor < valor {
- esquerda = meio + 1
+ if list.recordArray[middle].value < value {
+ left = middle + 1
} else {
- direita = meio - 1
+ right = middle - 1
}
}
return -1
}
-// Insere elementos na lista em ordem crescente, garantindo com a lista esteja sempre ordenada
-func insereRegistroOrdenado(lista *Lista, registro Registro) bool {
- if lista.numeroElementos == maxSize {
+// Inserts elements into the list in ascending order, ensuring that the list is always sorted
+func insertRecordInOrder(list *List, record Record) bool {
+ if list.numberOfElements == maxSize {
return false
}
- posicao := lista.numeroElementos
+ position := list.numberOfElements
- for posicao > 0 && lista.arranjoRegistros[posicao-1].valor > registro.valor {
- lista.arranjoRegistros[posicao] = lista.arranjoRegistros[posicao-1]
- posicao--
+ for position > 0 && list.recordArray[position-1].value > record.value {
+ list.recordArray[position] = list.recordArray[position-1]
+ position--
}
- lista.arranjoRegistros[posicao] = registro
- lista.numeroElementos++
+ list.recordArray[position] = record
+ list.numberOfElements++
return true
}
-// Exclui um elemento da lista
-func excluirElemento(lista *Lista, valor int) bool {
- posicao := buscaBinaria(lista, valor)
+// Deletes an element from the list
+func deleteElement(list *List, value int) bool {
+ position := binarySearch(list, value)
- if posicao == -1 {
+ if position == -1 {
return false
}
- for i := posicao; i < lista.numeroElementos-1; i++ {
- lista.arranjoRegistros[i] = lista.arranjoRegistros[i+1]
+ for i := position; i < list.numberOfElements-1; i++ {
+ list.recordArray[i] = list.recordArray[i+1]
}
- lista.numeroElementos--
+ list.numberOfElements--
return true
}
func main() {
- lista := criarLista()
+ list := createList()
- inicializar(&lista)
+ initialize(&list)
- fmt.Println("Inserindo valores na lista...")
- insereRegistroOrdenado(&lista, Registro{valor: 20})
- insereRegistroOrdenado(&lista, Registro{valor: 10})
- insereRegistroOrdenado(&lista, Registro{valor: 70})
- insereRegistroOrdenado(&lista, Registro{valor: 30})
- insereRegistroOrdenado(&lista, Registro{valor: 60})
- insereRegistroOrdenado(&lista, Registro{valor: 90})
- insereRegistroOrdenado(&lista, Registro{valor: 80})
- insereRegistroOrdenado(&lista, Registro{valor: 15})
- insereRegistroOrdenado(&lista, Registro{valor: 1})
+ fmt.Println("Inserting values into the list...")
+ insertRecordInOrder(&list, Record{value: 20})
+ insertRecordInOrder(&list, Record{value: 10})
+ insertRecordInOrder(&list, Record{value: 70})
+ insertRecordInOrder(&list, Record{value: 30})
+ insertRecordInOrder(&list, Record{value: 60})
+ insertRecordInOrder(&list, Record{value: 90})
+ insertRecordInOrder(&list, Record{value: 80})
+ insertRecordInOrder(&list, Record{value: 15})
+ insertRecordInOrder(&list, Record{value: 1})
fmt.Println()
- fmt.Println("Imprimindo lista...")
- imprimir(&lista)
- fmt.Println("Tamanho da lista:", tamanho(&lista))
+ fmt.Println("Printing the list...")
+ show(&list)
+ fmt.Println("Size of the list:", size(&list))
fmt.Println()
- fmt.Println("Excluindo elemento 80 da lista...")
- excluirElemento(&lista, 80)
+ fmt.Println("Deleting element 80 from the list...")
+ deleteElement(&list, 80)
fmt.Println()
- fmt.Println("Imprimindo lista...")
- imprimir(&lista)
- fmt.Println("Tamanho da lista:", tamanho(&lista))
+ fmt.Println("Printing the list...")
+ show(&list)
+ fmt.Println("Size of the list:", size(&list))
fmt.Println()
- fmt.Println("Buscando valores na lista:")
+ fmt.Println("Searching values in the list:")
fmt.Println()
- fmt.Println("Buscando posição do numero 15:")
- fmt.Printf("Posição do número 15: %v \n\n", buscaBinaria(&lista, 15))
+ fmt.Println("Searching position of number 15:")
+ fmt.Printf("Position of number 15: %v \n\n", binarySearch(&list, 15))
- fmt.Println("Buscando posição do valor 100:")
- fmt.Printf("Posição do número 100: %v \n\n", buscaBinaria(&lista, 100))
+ fmt.Println("Searching position of value 100:")
+ fmt.Printf("Position of number 100: %v \n\n", binarySearch(&list, 100))
}
diff --git a/src/go/stack.go b/src/go/stack.go
index 771d9f8b..8e13a1ce 100644
--- a/src/go/stack.go
+++ b/src/go/stack.go
@@ -26,12 +26,12 @@ func (stack *Stack[T]) Show() {
}
func main() {
- pilha := Stack[int]{}
- pilha.Push(1)
- pilha.Push(2)
- pilha.Push(3)
- pilha.Push(4)
- pilha.Pop()
+ stack := Stack[int]{}
+ stack.Push(1)
+ stack.Push(2)
+ stack.Push(3)
+ stack.Push(4)
+ stack.Pop()
fmt.Printf("Stack: ")
- pilha.Show()
+ stack.Show()
}
diff --git a/src/go/tower_of_hanoi.go b/src/go/tower_of_hanoi.go
index 42f8a39e..72f37624 100644
--- a/src/go/tower_of_hanoi.go
+++ b/src/go/tower_of_hanoi.go
@@ -4,7 +4,7 @@ import "fmt"
func Hanoi(pino0 int, pino2 int, pino1 int, numero int) {
if numero == 1 {
- fmt.Println("Mover de ", pino0, " para ", pino2)
+ fmt.Println("Move from ", pino0, " to ", pino2)
} else {
Hanoi(pino0, pino1, pino2, numero-1)
Hanoi(pino0, pino2, pino1, 1)
@@ -13,6 +13,6 @@ func Hanoi(pino0 int, pino2 int, pino1 int, numero int) {
}
func main() {
- fmt.Println("Torre de Hanoi:")
+ fmt.Println("Tower of Hanoi:")
Hanoi(0, 2, 1, 3)
}
diff --git a/src/go/travelling_salesman.go b/src/go/travelling_salesman.go
index 184e8a16..9d15564a 100644
--- a/src/go/travelling_salesman.go
+++ b/src/go/travelling_salesman.go
@@ -1,11 +1,10 @@
/*
- * O Problema do Caixeiro Viajante (PCV) eh um problema que tenta determinar a
- * menor rota para percorrer uma serie de cidades (visitando uma unica vez cada
- * uma delas), retornando a cidade de origem.
+ * The Traveling Salesman Problem (TSP) is a problem that tries to determine the
+ * shortest route to visit a series of cities (visiting each one only once), returning to the starting city.
*
- * Utilizando uma matriz de distancia para representar um grafo nao direcionado.
+ * Using a distance matrix to represent an undirected graph.
*
- * Supondo que temos o seguinte grafo:
+ * Assuming we have the following graph:
*
* 6
* -------------------
@@ -23,7 +22,7 @@
* -------------------
* 1
*
- * Matriz de Distancia
+ * Distance Matrix
* 0 1 2 3 4 5
* 0 0 3 6 2 3 -
* 1 3 0 1 6 8 2
@@ -32,7 +31,7 @@
* 4 3 8 4 6 0 4
* 5 - 2 5 1 4 0
*
- * Melhor solucao:
+ * Best solution:
* 0 - 3 - 5 - 1 - 2 - 4 - 0: 13
*/
@@ -41,113 +40,113 @@ package main
import "fmt"
const vertices = 6
-const infinito = 99999999
+const infinity = 99999999
-var matrizDistancia [][]int
+var distanceMatrix [][]int
-var tempSolucao []int // Solucao temporaria
-var melhorSolucao []int // Melhor solucao
-var visitados []bool // Vertices visitados
+var tempSolution []int // Temporary solution
+var bestSolution []int // Best solution
+var visited []bool // Visited vertices
-var valorMelhorSolucao int
-var valorSolucaoAtual int
+var bestSolutionValue int
+var currentSolutionValue int
-func CaixeiroViajanteAux(x int) {
+func TravelingSalesmanAux(x int) {
- // Significa que ja nao eh mais a melhor solucao podemos parar por aqui
- if valorSolucaoAtual > valorMelhorSolucao {
+ // If the current solution value is greater than the best solution value, it means it's no longer the best solution, so we can stop here
+ if currentSolutionValue > bestSolutionValue {
return
}
- // Significa que o vetor da solucao temporaria esta completo
+ // If the temporary solution vector is complete
if x == vertices {
- distancia := matrizDistancia[tempSolucao[x-1]][tempSolucao[0]]
+ distance := distanceMatrix[tempSolution[x-1]][tempSolution[0]]
- // Significa que encontrou uma solucao melhor
- if distancia < infinito && (valorSolucaoAtual+distancia) < valorMelhorSolucao {
+ // If a better solution is found
+ if distance < infinity && (currentSolutionValue+distance) < bestSolutionValue {
- // Temos uma solucao melhor
- valorMelhorSolucao = valorSolucaoAtual + distancia
+ // We have a better solution
+ bestSolutionValue = currentSolutionValue + distance
- // Copia todo o vetor para a melhor solucao
+ // Copy the entire vector to the best solution
for i := 0; i < vertices; i++ {
- melhorSolucao[i] = tempSolucao[i]
+ bestSolution[i] = tempSolution[i]
}
}
return
}
- // Ultimo vertice que se encontra na solucao temporaria
- ultimo := tempSolucao[x-1]
+ // Last vertex in the temporary solution
+ last := tempSolution[x-1]
- // Percorre todas as colunas da matriz de distancia na linha do ultimo vertice
+ // Iterate through all columns of the distance matrix in the row of the last vertex
for i := 0; i < vertices; i++ {
- // Se a posicao ainda nao foi visitada e o valor da matriz eh menor que infinito
- if !visitados[i] && matrizDistancia[ultimo][i] < infinito {
- // Marque a posicao como visitada
- visitados[i] = true
- // Carrega o vertice atual na solucao temporaria
- tempSolucao[x] = i
- // Incrementa o total do caminho percorrido com base na posicao da matriz
- valorSolucaoAtual += matrizDistancia[ultimo][i]
- // Chama recursivamente para o proximo vertice
- CaixeiroViajanteAux(x + 1)
- // Se ainda nao terminou decrementa o valor da variabel que guarta o total do caminho
- valorSolucaoAtual -= matrizDistancia[ultimo][i]
- // Define como nao visitada para poder ser acessada por outro vertice
- visitados[i] = false
+ // If the position has not been visited and the value in the matrix is less than infinity
+ if !visited[i] && distanceMatrix[last][i] < infinity {
+ // Mark the position as visited
+ visited[i] = true
+ // Load the current vertex into the temporary solution
+ tempSolution[x] = i
+ // Increment the total distance traveled based on the position in the matrix
+ currentSolutionValue += distanceMatrix[last][i]
+ // Call recursively for the next vertex
+ TravelingSalesmanAux(x + 1)
+ // If it has not finished yet, decrement the value of the variable that stores the total distance
+ currentSolutionValue -= distanceMatrix[last][i]
+ // Set it as not visited so it can be accessed by another vertex
+ visited[i] = false
}
}
}
-func CaixeiroViajante(posicaoInicial int) {
- // Verifica se a posicao eh valida
- if posicaoInicial < vertices {
- visitados[posicaoInicial] = true // Marca o primeiro vertice como visitado
- tempSolucao[0] = posicaoInicial // Coloca a posicao inicial na primeira posicao da solucao temporaria
- CaixeiroViajanteAux(1) // Chama o metodo auxiliar do caixeiro viajante
+func TravelingSalesman(initialPosition int) {
+ // Check if the position is valid
+ if initialPosition < vertices {
+ visited[initialPosition] = true // Mark the first vertex as visited
+ tempSolution[0] = initialPosition // Put the initial position in the first position of the temporary solution
+ TravelingSalesmanAux(1) // Call the auxiliary method for the traveling salesman
} else {
- fmt.Println("Vertice inicial invalid")
+ fmt.Println("Invalid initial vertex")
}
}
-// Inicia os vetores e valores padrao
-func inicia() {
+// Initialize vectors and default values
+func initialize() {
- valorMelhorSolucao = infinito
- valorSolucaoAtual = 0
+ bestSolutionValue = infinity
+ currentSolutionValue = 0
for i := 0; i < vertices; i++ {
- visitados = append(visitados, false)
- tempSolucao = append(tempSolucao, -1)
- melhorSolucao = append(melhorSolucao, -1)
+ visited = append(visited, false)
+ tempSolution = append(tempSolution, -1)
+ bestSolution = append(bestSolution, -1)
}
- // Cria a matriz de distancia
- linha0 := []int{0, 3, 6, 2, 3, infinito}
- linha1 := []int{3, 0, 1, 6, 8, 2}
- linha2 := []int{6, 1, 0, infinito, 4, 5}
- linha3 := []int{2, 6, infinito, 0, 6, 1}
- linha4 := []int{3, 8, 4, 6, 0, 4}
- linha5 := []int{infinito, 2, 5, 1, 4, 0}
-
- matrizDistancia = append(matrizDistancia, linha0)
- matrizDistancia = append(matrizDistancia, linha1)
- matrizDistancia = append(matrizDistancia, linha2)
- matrizDistancia = append(matrizDistancia, linha3)
- matrizDistancia = append(matrizDistancia, linha4)
- matrizDistancia = append(matrizDistancia, linha5)
+ // Create the distance matrix
+ row0 := []int{0, 3, 6, 2, 3, infinity}
+ row1 := []int{3, 0, 1, 6, 8, 2}
+ row2 := []int{6, 1, 0, infinity, 4, 5}
+ row3 := []int{2, 6, infinity, 0, 6, 1}
+ row4 := []int{3, 8, 4, 6, 0, 4}
+ row5 := []int{infinity, 2, 5, 1, 4, 0}
+
+ distanceMatrix = append(distanceMatrix, row0)
+ distanceMatrix = append(distanceMatrix, row1)
+ distanceMatrix = append(distanceMatrix, row2)
+ distanceMatrix = append(distanceMatrix, row3)
+ distanceMatrix = append(distanceMatrix, row4)
+ distanceMatrix = append(distanceMatrix, row5)
}
func main() {
- inicia()
- CaixeiroViajante(0)
+ initialize()
+ TravelingSalesman(0)
- fmt.Println("Caixeiro Viajante")
- fmt.Println("Caminho minimo:", valorMelhorSolucao)
+ fmt.Println("Traveling Salesman")
+ fmt.Println("Minimum path:", bestSolutionValue)
for i := 0; i < vertices; i++ {
- fmt.Print(melhorSolucao[i], ", ")
+ fmt.Print(bestSolution[i], ", ")
}
- fmt.Println(melhorSolucao[0])
+ fmt.Println(bestSolution[0])
}
diff --git a/src/go/unordered_linked_list.go b/src/go/unordered_linked_list.go
index 87dd5d2c..b40eb68a 100644
--- a/src/go/unordered_linked_list.go
+++ b/src/go/unordered_linked_list.go
@@ -1,9 +1,9 @@
/*
-* Listas - Lista linear não ordenada
+* Lists - Unordered linear list
*
-* Implementação da lista sequencial cujos elementos não estão ordenados
+* Implementation of a sequential list where elements are not ordered
*
-* link Go PlayGround: https://play.golang.org/p/3uFOquVlTD8
+* Go Playground link: https://play.golang.org/p/3uFOquVlTD8
*/
package main
@@ -12,51 +12,51 @@ import "fmt"
var maxSize = 50
-// Estrura que será guardada em cada posição da lista
-type Registro struct {
- valor int
- // Outros campos podem ser adicionados aqui
+// Structure that will be stored in each position of the list
+type Record struct {
+ value int
+ // Other fields can be added here
}
-// Estrutura que guarda um arranjo de Registro, e o número de elementos no arranjo
-type Lista struct {
- arranjoRegistros []Registro
- numeroElementos int
+// Structure that holds an array of Records and the number of elements in the array
+type List struct {
+ recordArray []Record
+ numberOfElements int
}
-// Cria uma nova lista
-func criarLista() Lista {
- lista := Lista{
- arranjoRegistros: make([]Registro, maxSize),
- numeroElementos: 0,
+// Creates a new list
+func createList() List {
+ list := List{
+ recordArray: make([]Record, maxSize),
+ numberOfElements: 0,
}
- return lista
+ return list
}
-// reseta o contador de elementos da lista
-func inicializar(lista *Lista) {
- lista.numeroElementos = 0
+// Resets the list's element counter
+func initialize(list *List) {
+ list.numberOfElements = 0
}
-// Recupera a quantidade de elementos da lista
-func tamanho(lista *Lista) int {
- return lista.numeroElementos
+// Retrieves the number of elements in the list
+func size(list *List) int {
+ return list.numberOfElements
}
-// Imprime valores dos elementos na lista
-func imprimir(lista *Lista) {
- for i := 0; i < lista.numeroElementos; i++ {
- fmt.Printf("%v ", lista.arranjoRegistros[i].valor)
+// Prints the values of the elements in the list
+func show(list *List) {
+ for i := 0; i < list.numberOfElements; i++ {
+ fmt.Printf("%v ", list.recordArray[i].value)
}
fmt.Println()
}
-// Realiza busca sequencial na lista, percorrendo item por item
-func buscaSequencial(lista *Lista, valor int) int {
+// Performs a sequential search in the list, iterating through each item
+func sequentialSearch(list *List, value int) int {
i := 0
- for i < lista.numeroElementos {
- if valor == lista.arranjoRegistros[i].valor {
+ for i < list.numberOfElements {
+ if value == list.recordArray[i].value {
return i
}
i++
@@ -64,92 +64,92 @@ func buscaSequencial(lista *Lista, valor int) int {
return -1
}
-// Realiza busca sentinela na lista, percorrendo item por item
-func buscaSentinela(lista *Lista, valor int) int {
+// Performs a sentinel search in the list, iterating through each item
+func sentinelSearch(list *List, value int) int {
i := 0
- lista.arranjoRegistros[lista.numeroElementos].valor = valor
+ list.recordArray[list.numberOfElements].value = value
- for valor != lista.arranjoRegistros[i].valor {
+ for value != list.recordArray[i].value {
i++
}
- if i == lista.numeroElementos {
+ if i == list.numberOfElements {
return -1
}
return i
}
-// Insere elementos na lista, em uma posição específica, e move todos os outros elementos para a direita
-func insereElemento(lista *Lista, registro Registro, posicao int) bool {
- if (lista.numeroElementos == maxSize) || posicao < 0 || posicao > lista.numeroElementos {
+// Inserts elements into the list at a specific position and moves all other elements to the right
+func insertElement(list *List, record Record, position int) bool {
+ if (list.numberOfElements == maxSize) || position < 0 || position > list.numberOfElements {
return false
}
- for j := lista.numeroElementos; j > posicao; j-- {
- lista.arranjoRegistros[j] = lista.arranjoRegistros[j-1]
+ for j := list.numberOfElements; j > position; j-- {
+ list.recordArray[j] = list.recordArray[j-1]
}
- lista.arranjoRegistros[posicao] = registro
- lista.numeroElementos++
+ list.recordArray[position] = record
+ list.numberOfElements++
return true
}
-// Exclui um elemento da lista
-func excluirElemento(lista *Lista, valor int) bool {
- posicao := buscaSequencial(lista, valor)
+// Deletes an element from the list
+func deleteElement(list *List, value int) bool {
+ position := sequentialSearch(list, value)
- if posicao == -1 {
+ if position == -1 {
return false
}
- for i := posicao; i < lista.numeroElementos-1; i++ {
- lista.arranjoRegistros[i] = lista.arranjoRegistros[i+1]
+ for i := position; i < list.numberOfElements-1; i++ {
+ list.recordArray[i] = list.recordArray[i+1]
}
- lista.numeroElementos--
+ list.numberOfElements--
return true
}
func main() {
- lista := criarLista()
+ list := createList()
- inicializar(&lista)
+ initialize(&list)
- fmt.Println("Inserindo valores na lista...")
- insereElemento(&lista, Registro{valor: 20}, 0)
- insereElemento(&lista, Registro{valor: 10}, 0)
- insereElemento(&lista, Registro{valor: 70}, 0)
- insereElemento(&lista, Registro{valor: 30}, 0)
- insereElemento(&lista, Registro{valor: 60}, 0)
- insereElemento(&lista, Registro{valor: 90}, 0)
- insereElemento(&lista, Registro{valor: 80}, 0)
- insereElemento(&lista, Registro{valor: 15}, 0)
- insereElemento(&lista, Registro{valor: 1}, 0)
+ fmt.Println("Inserting values into the list...")
+ insertElement(&list, Record{value: 20}, 0)
+ insertElement(&list, Record{value: 10}, 0)
+ insertElement(&list, Record{value: 70}, 0)
+ insertElement(&list, Record{value: 30}, 0)
+ insertElement(&list, Record{value: 60}, 0)
+ insertElement(&list, Record{value: 90}, 0)
+ insertElement(&list, Record{value: 80}, 0)
+ insertElement(&list, Record{value: 15}, 0)
+ insertElement(&list, Record{value: 1}, 0)
fmt.Println()
- fmt.Println("Imprimindo lista...")
- imprimir(&lista)
- fmt.Println("Tamanho da lista:", tamanho(&lista))
+ fmt.Println("Printing the list...")
+ show(&list)
+ fmt.Println("Size of the list:", size(&list))
fmt.Println()
- fmt.Println("Excluindo elemento 80 da lista...")
- excluirElemento(&lista, 80)
+ fmt.Println("Deleting element 80 from the list...")
+ deleteElement(&list, 80)
fmt.Println()
- fmt.Println("Imprimindo lista...")
- imprimir(&lista)
- fmt.Println("Tamanho da lista:", tamanho(&lista))
+ fmt.Println("Printing the list...")
+ show(&list)
+ fmt.Println("Size of the list:", size(&list))
fmt.Println()
- fmt.Println("Buscando valores na lista:")
+ fmt.Println("Searching for values in the list:")
fmt.Println()
- fmt.Println("Buscando posição do numero 15:")
- fmt.Printf("Posição do número 15: %v \n\n", buscaSequencial(&lista, 15))
+ fmt.Println("Searching for the position of number 15:")
+ fmt.Printf("Position of number 15: %v \n\n", sequentialSearch(&list, 15))
- fmt.Println("Buscando posição do valor 100:")
- fmt.Printf("Posição do número 100: %v \n\n", buscaSequencial(&lista, 100))
+ fmt.Println("Searching for the position of value 100:")
+ fmt.Printf("Position of number 100: %v \n\n", sequentialSearch(&list, 100))
}
diff --git a/src/kotlin/ExponentiationRecursive.kt b/src/kotlin/ExponentiationRecursive.kt
index bb6039a5..95b21122 100644
--- a/src/kotlin/ExponentiationRecursive.kt
+++ b/src/kotlin/ExponentiationRecursive.kt
@@ -9,13 +9,15 @@
*
* @return will return the *base* number raised by the *exponent*. The function returns a value of type *Long*.
*/
-fun exponentiationRecursive(base: Int, exponent: Int): Long {
- return if (exponent === 0) {
+fun exponentiationRecursive(
+ base: Int,
+ exponent: Int,
+): Long =
+ if (exponent === 0) {
1
- }; else {
+ } else {
base * exponentiationRecursive(base, exponent - 1)
}
-}
fun main() {
println(exponentiationRecursive(2, 3))
diff --git a/src/kotlin/FibonacciRecursive.kt b/src/kotlin/FibonacciRecursive.kt
index 7dc666d7..7874e0b5 100644
--- a/src/kotlin/FibonacciRecursive.kt
+++ b/src/kotlin/FibonacciRecursive.kt
@@ -8,13 +8,12 @@
*
* @return will return a logical condition if *number* is less than or equal to 1, returns 1 otherwise, the sum of itself using the concept of *recursion* to execute this sum.
*/
-fun fibonacci(number: Int): Int {
- return if (number <= 1) {
+fun fibonacci(number: Int): Int =
+ if (number <= 1) {
1
- }; else {
+ } else {
fibonacci(number - 1) + fibonacci(number - 2)
}
-}
fun main() {
println(fibonacci(5))
diff --git a/src/kotlin/MergeSort.kt b/src/kotlin/MergeSort.kt
index dd874bae..93ce92b7 100644
--- a/src/kotlin/MergeSort.kt
+++ b/src/kotlin/MergeSort.kt
@@ -10,7 +10,10 @@ fun mergeSort(arr: IntArray): IntArray {
return merge(mergeSort(left), mergeSort(right))
}
-fun merge(left: IntArray, right: IntArray): IntArray {
+fun merge(
+ left: IntArray,
+ right: IntArray,
+): IntArray {
var result = IntArray(left.size + right.size)
var leftIndex = 0
var rightIndex = 0
diff --git a/src/python/binary_search.py b/src/python/binary_search.py
index b85e4262..acfc880c 100644
--- a/src/python/binary_search.py
+++ b/src/python/binary_search.py
@@ -1,30 +1,30 @@
-""" Implementação do algoritmo de busca binária com recursão """
+""" Recursive Binary Search Algorithm in Python """
-def busca_binaria(valor, vetor, esquerda, direita):
+def binary_search(value, vector, left, right):
"""
- Implementação de um algoritmo de busca binária com recursão.
+ Implementation of a binary search algorithm with recursion.
- Argumentos:
- valor: Any. Valor a ser buscado na lista
- vetor: list. lista ordenada na qual o valor será buscado
- esquerda: Any. Valor inicial da metade buscada
- direita: Any. Valor final da metade buscada
+ Arguments:
+ value: Any. Value to be searched for in the list
+ vector: List. Ordered list in which value will be searched for
+ left: Any. Leftmost index for binary search
+ right: Any. Rightmost index for binary search
- Retorna o índice do valor em "vetor" ou -1 caso não exista nela.
+ Returns the index of value in vector; returns -1 if value not found in vector
"""
- meio = int((esquerda + direita) / 2)
+ middle = int((left + right) / 2)
- if esquerda <= direita:
- if valor > vetor[meio]:
- esquerda = meio + 1
- return busca_binaria(valor, vetor, esquerda, direita)
- elif valor < vetor[meio]:
- direita = meio - 1
- return busca_binaria(valor, vetor, esquerda, direita)
- return meio
+ if left <= right:
+ if value > vector[middle]:
+ left = middle + 1
+ return binary_search(value, vector, left, right)
+ elif value < vector[middle]:
+ right = middle - 1
+ return binary_search(value, vector, left, right)
+ return middle
return -1
-lista = [0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12]
-print(busca_binaria(12, lista, 0, len(lista) - 1))
+list = [0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12]
+print(binary_search(12, list, 0, len(list) - 1))
diff --git a/src/python/binary_search_tree.py b/src/python/binary_search_tree.py
index 6cdfc481..2b7fa910 100644
--- a/src/python/binary_search_tree.py
+++ b/src/python/binary_search_tree.py
@@ -1,6 +1,4 @@
-"""
-Arvore Binaria de Busca em Python
-"""
+""" Binary Search Tree in Python """
class TreeNode:
diff --git a/src/python/binary_tree.py b/src/python/binary_tree.py
index 8945200a..ede3fa47 100644
--- a/src/python/binary_tree.py
+++ b/src/python/binary_tree.py
@@ -1,4 +1,4 @@
-""" Implementação de uma árvore binária """
+""" Binary Tree in Python """
class Node:
diff --git a/src/python/bubble_sort.py b/src/python/bubble_sort.py
index 232e310a..7730f855 100755
--- a/src/python/bubble_sort.py
+++ b/src/python/bubble_sort.py
@@ -1,4 +1,4 @@
-""" Implementation of the bubble sort algorithm with recursion """
+""" Recursive Bubble Sort in Python """
def bubble_sort(data, size):
@@ -9,7 +9,7 @@ def bubble_sort(data, size):
data: list. List to be sorted
size: int. List size
- Returns the ordered "date" list.
+ Returns the ordered "data" list.
"""
swap = False
for i in range(0, size - 1):
diff --git a/src/python/calculate_pi.py b/src/python/calculate_pi.py
index 00892776..9a7ae1b4 100644
--- a/src/python/calculate_pi.py
+++ b/src/python/calculate_pi.py
@@ -1,14 +1,14 @@
-""" Implementaço de um algoritmo de cálculo do PI """
+""" Calculating PI in Python """
def calculate_pi(number):
"""
- Implementação de um algoritmo de cálculo do PI.
+ Implementation of a PI calculation algorithm.
- Argumentos:
+ Arguments:
number: int.
- Retorna o valor de PI.
+ Returns the value of PI.
"""
denominator = 1.0
operation = 1.0
diff --git a/src/python/circular_linked_list.py b/src/python/circular_linked_list.py
index f4806b83..a65b2f61 100644
--- a/src/python/circular_linked_list.py
+++ b/src/python/circular_linked_list.py
@@ -1,4 +1,4 @@
-""" implementação de uma lista encadeada circular """
+""" Implementation of a circular linked list in Python """
import unittest
diff --git a/src/python/comb_sort.py b/src/python/comb_sort.py
index 01a5810c..8adde32f 100644
--- a/src/python/comb_sort.py
+++ b/src/python/comb_sort.py
@@ -1,13 +1,9 @@
-#!/usr/bin/env python3
-# -*- coding: utf-8 -*-
-# ----------------------------------------------------------------------------
-# Created By : octaviolage
-# Created Date: 2022-05-15
-# version ='1.0'
-# -------------------------------
+""" Comb Sort in Python """
+
+
def comb_sort(arr: list) -> list:
"""
- Implementação de um algoritmo de ordenação combinada.
+ Implementation of comb sort algorithm
"""
gap = len(arr)
shrink = 1.3
@@ -28,5 +24,5 @@ def comb_sort(arr: list) -> list:
from random import randint
my_list = [randint(0, 100) for _ in range(10)]
- print(f"Lista: {my_list}")
- print(f"Ordenada: {comb_sort(my_list)}")
+ print(f"List: {my_list}")
+ print(f"Sorted list: {comb_sort(my_list)}")
diff --git a/src/python/counting_sort.py b/src/python/counting_sort.py
index a113be1e..fec1bae6 100644
--- a/src/python/counting_sort.py
+++ b/src/python/counting_sort.py
@@ -1,27 +1,27 @@
-# Algoritmo de ordenação Counting sort em Python
+""" Counting sort in Python """
import random
def counting_sort(arr):
- # Encontra o maior elemento na lista
+ """Finding the max element in the list"""
k = max(arr) + 1
- # Inicializa o array de contagem com zeros
+ """ Initialing count array of len k with 0's """
count = [0] * k
- # Conta a frequência de cada elemento
+ """ Counts frequency of each element """
for i in arr:
count[i] += 1
- # Atualiza o array de contagem para refletir a posição correta de cada elemento na lista ordenada
+ """ Updates count array to reflect the correct position of each element in the sorted list """
for i in range(1, k):
count[i] += count[i - 1]
- # Inicializa o array de resultado com zeros
+ """ Initializing result list with 0's """
result = [0] * len(arr)
- # Preenche o array de resultado com os elementos ordenados
+ """ Fill result array with the sorted elements"""
for i in reversed(arr):
result[count[i] - 1] = i
count[i] -= 1
@@ -29,15 +29,15 @@ def counting_sort(arr):
return result
-# Gera uma lista de n números aleatórios
+""" Generate a list of n random integers """
n = 10
-lista = [random.randint(0, 100) for _ in range(n)]
+list = [random.randint(0, 100) for _ in range(n)]
-# Imprime a lista original sem ordenação
-print(f"Lista Original: {lista}")
+""" Prints original, unsorted list"""
+print(f"List: {list}")
-# Ordena a lista utilizando o algoritmo de Counting Sort
-lista_ordenada = counting_sort(lista)
+""" Sorts list using counting sort algorithm """
+sorted_list = counting_sort(list)
-# Imprime a lista ordenada
-print(f"Lista Ordenada: {lista_ordenada}")
+""" Prints sorted list """
+print(f"Sorted list: {sorted_list}")
diff --git a/src/python/doubly_linked_list.py b/src/python/doubly_linked_list.py
index 7b800113..1f4b73d7 100644
--- a/src/python/doubly_linked_list.py
+++ b/src/python/doubly_linked_list.py
@@ -1,8 +1,8 @@
"""
-Lista Duplamente Encadeada
+Doubly Linked List
-A cabeca da lista sempre 'aponta' para o primeiro no
-O rabo da lista sempre 'aponta' para o ultimo no
+The 'head' of the list always points to the first node
+The 'tail' of the list always points to the final node
None <--- | 2 | ---> None
None <--- | 2 | <---> | 5 | ---> None
@@ -11,102 +11,97 @@
"""
-class No:
- def __init__(self, dado, anterior, proximo):
- self.dado = dado
- self.anterior = anterior
- self.proximo = proximo
+class Node:
+ def __init__(self, data, prev, next):
+ self.data = data
+ self.prev = prev
+ self.next = next
-class ListaDuplamenteEncadeada:
- cabeca = None
- rabo = None
+class DoublyLinkedList:
+ head = None
+ tail = None
- def acrescentar(self, dado):
- """Acrescenta um novo no a lista."""
- # Cria um novo no apontando para None (anterior e proximo)
- novo_no = No(dado, None, None)
+ def append(self, data):
+ # Creates a new node pointing to None (prev and next)
+ new_node = Node(data, None, None)
- # Se a cabeca eh None a lista esta vazia
- # Tanto a cabeca quanto o rabo recebem o novo no
- if self.cabeca is None:
- self.cabeca = novo_no
- self.rabo = novo_no
- # Caso contrario, se ja existir algum valor na lista
+ # If the list is empty, both head and tail point to the new node
+ if self.head is None:
+ self.head = new_node
+ self.tail = new_node
else:
- # O anterior 'aponta' para o rabo (ultimo no adicionado)
- novo_no.anterior = self.rabo
- # O proximo sempre aponta para None
- novo_no.proximo = None
- # O proximo do rabo sempre aponta para o novo no
- self.rabo.proximo = novo_no
- # O rabo agora eh o novo no
- self.rabo = novo_no
-
- def remover(self, dado):
- """Remove um no da lista."""
- # O no atual eh o primeiro no da lista
- no_atual = self.cabeca
-
- # Vamos procurar pelo dado que queremos remover
- # Equanto o no atual for valido
- while no_atual is not None:
+ # For a non-empty list, adjust pointers to add the new node at the end
+ new_node.prev = self.tail # New node's prev points to the current tail
+ self.tail.next = new_node # Current tail's next points to the new node
+ self.tail = new_node # Update tail to be the new node
+
+ # No additional 'new_node.next = None' is needed as it's already None by default
+
+ def delete(self, data):
+ """Deletes a node from the list"""
+ """ Current node is first node in the list"""
+ curr_node = self.head
+
+ # We search for the data we want to delete
+ # While current node is not invalid
+ while curr_node is not None:
# Verifica se eh o dado que estamos buscando
- if no_atual.dado == dado:
- # Se o dado que estamos buscando esta no primeiro no
- # da lista, nao temos anterior
- if no_atual.anterior is None:
- # A cabeca 'aponta' para o proximo no da lista
- self.cabeca = no_atual.proximo
- # E o anterior do proximo no aponta para None
- no_atual.proximo.anterior = None
+ if curr_node.data == data:
+ # If data we are looking for is in first node
+ # If we do not have a previous node in the list
+ if curr_node.prev is None:
+ # Head points to next node in the list
+ self.head = curr_node.next
+ # And the previous of the next node does not point to None
+ curr_node.next.prev = None
else:
- # Exemplo: Removendo o valor 5
+ # Example: Deleting the value 5
# ... <---> | 2 | <---> | 5 | <---> | 12 | <---> ...
#
- # O proximo do valor 2 passa a apontar para o 12 e
- # o anterior do valor 12 passa a apontar para o 2
+ # Next node of 2 will now point to 12 instead of 5
+ # Previous node of 12 will not point to 2 instead of 5
# ---------------
# ... <---> | 2 | <---|--- | 5 | ---|---> | 12 | <---> ...
- no_atual.anterior.proximo = no_atual.proximo
- no_atual.proximo.anterior = no_atual.anterior
-
- # Se nao eh o no que estamos buscando va para o proximo
- no_atual = no_atual.proximo
-
- def mostrar(self):
- """Mostra todos os dados da lista."""
- print("Lista Duplamente Encadeada:")
-
- # O no atual eh o primeiro no da lista
- no_atual = self.cabeca
-
- no = ""
- # Para cada no valido da lista
- while no_atual is not None:
- if no_atual.anterior is None:
- no += "None "
- no += "<---> | " + str(no_atual.dado) + " | "
- if no_atual.proximo is None:
- no += "<---> None"
-
- no_atual = no_atual.proximo
- print(no)
+ curr_node.prev.next = curr_node.next
+ curr_node.next.prev = curr_node.prev
+
+ # If current node does not hold desired data, move to next node
+ curr_node = curr_node.next
+
+ def display(self):
+ """Displays all data in the list"""
+ print("Doubly Linked List: ")
+
+ # Current node is head of the list
+ curr_node = self.head
+
+ node = ""
+ # For each valid node in the list
+ while curr_node is not None:
+ if curr_node.prev is None:
+ node += "None "
+ node += "<---> | " + str(curr_node.data) + " | "
+ if curr_node.next is None:
+ node += "<---> None"
+
+ curr_node = curr_node.next
+ print(node)
print("=" * 80)
-lista = ListaDuplamenteEncadeada()
+list = DoublyLinkedList()
-lista.acrescentar(2)
-lista.mostrar()
-lista.acrescentar(5)
-lista.mostrar()
-lista.acrescentar(12)
-lista.mostrar()
-lista.acrescentar(20)
-lista.mostrar()
+list.append(2)
+list.display()
+list.append(5)
+list.display()
+list.append(12)
+list.display()
+list.append(20)
+list.display()
-lista.remover(12)
-lista.mostrar()
-lista.remover(5)
-lista.mostrar()
+list.delete(12)
+list.display()
+list.delete(5)
+list.display()
diff --git a/src/python/dynamic_stack.py b/src/python/dynamic_stack.py
index e6743984..129b73a8 100644
--- a/src/python/dynamic_stack.py
+++ b/src/python/dynamic_stack.py
@@ -41,7 +41,7 @@ def show(self) -> None:
def main() -> None:
dynamic_stack = DynamicStack()
- print(f"Push(1,2,4):")
+ print("Push(1,2,4):")
dynamic_stack.push(1)
dynamic_stack.push(2)
dynamic_stack.push(4)
diff --git a/src/python/exponentiation.py b/src/python/exponentiation.py
index 17cf2d91..e54f9f38 100644
--- a/src/python/exponentiation.py
+++ b/src/python/exponentiation.py
@@ -1,21 +1,22 @@
-""" Algoritmo de exponenciação """
+""" Iterative exponentiation algorithm """
-def exponenciacao(base, expoente):
+def exponentiation(base, exponent):
"""
- Implementação de um algoritmo de exponenciação.
+ Implementation of an exponentiation algorithm.
- Argumentos:
- base: int. Base da operação
- expoente: int. Expoente da operação.
+ Arguments:
+ base (int): Base of operation
+ exponent (int): Exponent of operation
- Retorna o resultado da operação de exponenciação
+ Returns:
+ Returns the result of the exponentiation operation.
"""
result = base
- for _ in range(0, expoente - 1):
+ for _ in range(0, exponent - 1):
result *= base
return result
-print(exponenciacao(5, 2))
-print(exponenciacao(5, 5))
+print(exponentiation(5, 2))
+print(exponentiation(5, 5))
diff --git a/src/python/exponentiation_recursive.py b/src/python/exponentiation_recursive.py
index d38aacda..1db76fd2 100644
--- a/src/python/exponentiation_recursive.py
+++ b/src/python/exponentiation_recursive.py
@@ -1,22 +1,23 @@
-""" Algoritmo de exponenciação implementado com recursão. """
+""" Recursive exponentiation algorithm """
-def exponenciacao_recursiva(base, expoente):
- """Implementação de um algoritmo de exponenciação.
+def exponentiation_recursive(base, exponent):
+ """
+ Implementation of an exponentiation algorithm using recursion.
- Args:
- base (int): Base da operação
- expoente (int): Expoente da operação
+ Arguments:
+ base (int): Base of operation
+ exponent (int): Exponent of operation
Returns:
- Retorna o resultado da operaçao de exponenciação.
+ Returns the result of the exponentiation operation.
"""
- if expoente == 0:
+ if exponent == 0:
return 1
- return base * exponenciacao_recursiva(base, expoente - 1)
+ return base * exponentiation_recursive(base, exponent - 1)
if __name__ == "__main__":
- print(exponenciacao_recursiva(5, 2))
- print(exponenciacao_recursiva(5, 5))
+ print(exponentiation_recursive(5, 2))
+ print(exponentiation_recursive(5, 5))
diff --git a/src/python/factorial.py b/src/python/factorial.py
index 31146ba8..48ef04c4 100644
--- a/src/python/factorial.py
+++ b/src/python/factorial.py
@@ -1,14 +1,14 @@
-""" Uma implementação simples de um algoritmo fatorial """
+""" Iterative factorial algorithm """
-def fatorial(num):
+def factorial(num):
"""
- Uma implementação simples de um algoritmo de fatorial.
+ Implementation of the factorial algorithm iteratively.
- Argumentos:
- num: int. o número do qual deseja-se obter o fatorial.
+ Arguments:
+ num: int. the number of which you want to obtain the factorial.
- Retorna o resultado da operação.
+ Returns the result of the factorial operation
"""
aux = 1
for i in range(2, num + 1):
@@ -17,4 +17,4 @@ def fatorial(num):
if __name__ == "__main__":
- print(fatorial(5))
+ print(factorial(5))
diff --git a/src/python/factorial_recursive.py b/src/python/factorial_recursive.py
index cec8de56..d497d22d 100644
--- a/src/python/factorial_recursive.py
+++ b/src/python/factorial_recursive.py
@@ -1,19 +1,19 @@
-""" Algoritmo de fatorial implementado com recursão """
+""" Recursive factorial algorithm """
-def fatorial_recursivo(numero):
+def factorial_recursive(num):
"""
- Implementação de um algoritmo de fatorial com recursão.
+ Implementation of factorial algorithm using recursion
- Argumentos:
- numero: int. o número do qual deseja-se obter o fatorial.
+ Arguments:
+ num: int. the number of which you want to obtain the factorial.
- Retorna o resultado da operação.
+ Returns the result of the factorial operation
"""
- if numero == 1:
+ if num == 1:
return 1
- return numero * fatorial_recursivo(numero - 1)
+ return num * factorial_recursive(num - 1)
-print(fatorial_recursivo(5))
+print(factorial_recursive(5))
diff --git a/src/python/fibonacci_iterative.py b/src/python/fibonacci_iterative.py
index 2df05079..a7ad7dc9 100755
--- a/src/python/fibonacci_iterative.py
+++ b/src/python/fibonacci_iterative.py
@@ -1,11 +1,10 @@
"""
-Implementaço de vários algoritmos Fibonacci
+Iterative Fibonacci Algorithm
-A lib "time" foi utilizada para marcar o tempo de
-execução dos algoritmos em segundos
+The lib "time" was used to mark the time of
+execution of algorithms in seconds
"""
-import functools
import time
@@ -20,13 +19,13 @@ def fibonacci(number):
def main(name, func, number=35):
"""
- Roda o algoritmo e mostra o tempo de execução dele
+ Run iterative algorithm and show its execution time
"""
start_time = time.time()
result = func(number)
diff_time = time.time() - start_time
- print("Fibonacci", name, ":", result, ":", "%.8f" % diff_time, "segundos")
+ print("Fibonacci", name, ":", result, ":", "%.8f" % diff_time, "seconds")
if __name__ == "__main__":
- main("Iterativa", fibonacci)
+ main("Iterative", fibonacci)
diff --git a/src/python/fibonacci_memoization.py b/src/python/fibonacci_memoization.py
index 1ff01958..1a8c8e6e 100644
--- a/src/python/fibonacci_memoization.py
+++ b/src/python/fibonacci_memoization.py
@@ -1,10 +1,16 @@
+"""
+Recursive Fibonacci Algorithm using a Cache
+"""
+
import functools
import time
@functools.lru_cache(maxsize=None)
def fibonacci(number):
- """Fibonacci recursiva com cache."""
+ """
+ Recursive fibonacci algorithm with cache
+ """
if number < 2:
return number
return fibonacci(number - 1) + fibonacci(number - 2)
@@ -12,13 +18,13 @@ def fibonacci(number):
def main(name, func, number=35):
"""
- Roda o algoritmo e mostra o tempo de execução dele
+ Run algorithm and show its execution time
"""
start_time = time.time()
result = func(number)
diff_time = time.time() - start_time
- print("Fibonacci", name, ":", result, ":", "%.8f" % diff_time, "segundos")
+ print("Fibonacci", name, ":", result, ":", "%.8f" % diff_time, "seconds")
if __name__ == "__main__":
- main("Fibonacci Memoization:", fibonacci)
+ main("Memorization:", fibonacci)
diff --git a/src/python/fibonacci_recursive.py b/src/python/fibonacci_recursive.py
index 1bbba363..106d7f36 100644
--- a/src/python/fibonacci_recursive.py
+++ b/src/python/fibonacci_recursive.py
@@ -1,15 +1,18 @@
"""
-Implementaço de vários algoritmos Fibonacci
+Recursive Fibonacci Algorithm
-A lib "time" foi utilizada para marcar o tempo de
-execução dos algoritmos em segundos
+The lib "time" was used to mark the time of
+execution of algorithms in seconds
"""
import time
def fibonacci(number):
- """Fibonnaci recursiva."""
+ """
+ Recursive Fibonacci
+ """
+
if number < 2:
return number
return fibonacci(number - 1) + fibonacci(number - 2)
@@ -17,13 +20,13 @@ def fibonacci(number):
def main(name, func, number=35):
"""
- Roda o algoritmo e mostra o tempo de execução dele
+ Run the algorithm and show its execution time
"""
start_time = time.time()
result = func(number)
diff_time = time.time() - start_time
- print("Fibonacci", name, ":", result, ":", "%.8f" % diff_time, "segundos")
+ print("Fibonacci", name, ":", result, ":", "%.8f" % diff_time, "seconds")
if __name__ == "__main__":
- main("Recursiva", fibonacci)
+ main("Recursive", fibonacci)
diff --git a/src/python/insertion_sort.py b/src/python/insertion_sort.py
index 431972e1..b97eef95 100644
--- a/src/python/insertion_sort.py
+++ b/src/python/insertion_sort.py
@@ -1,59 +1,63 @@
-"""Implementação do algoritmo insertion sort iterativo e recursivo."""
+""" Insertion Sort in Python (Iterative and Recursive) """
-def insertion_sort_iterativo(vetor):
+def insertion_sort_iterative(vector):
"""
- Implementação do algoritmo de insertion sort iterativo.
+ Implementation of insertion sort iteratively.
- Args:
- vetor (list): lista que será ordenada.
+ Arguments:
+ vector (list): list to be sorted.
Returns:
- Retorna a lista ordenada.
+ Returns the sorted list.
"""
- for i in range(1, len(vetor)):
- chave = vetor[i]
+ for i in range(1, len(vector)):
+ key = vector[i]
aux = i - 1
- while aux >= 0 and vetor[aux] > chave:
- vetor[aux + 1] = vetor[aux]
+ while aux >= 0 and vector[aux] > key:
+ vector[aux + 1] = vector[aux]
aux -= 1
- vetor[aux + 1] = chave
- return vetor
+ vector[aux + 1] = key
+ return vector
-def insertion_sort_recursivo(vetor, indice):
+def insertion_sort_recursive(vector, index):
"""
- Implementação do algoritmo de insertion sort recursivo.
+ Implementation of insertion sort recursively.
- Args:
- vetor (list): lista que será ordenada.
- indice (int): índice do elemento a ser ordenado na lista.
+ Arguments:
+ vector (list): list to be sorted.
+ index (int): index of the element to be sorted in the list.
Returns:
- Retorna a lista ordenada.
+ Returns the sorted list.
"""
- aux = indice
- while vetor[aux] < vetor[aux - 1]:
- temp = vetor[aux]
- vetor[aux] = vetor[aux - 1]
- vetor[aux - 1] = temp
+ aux = index
+ while vector[aux] < vector[aux - 1]:
+ temp = vector[aux]
+ vector[aux] = vector[aux - 1]
+ vector[aux - 1] = temp
aux -= 1
if aux == 0:
break
- if indice < len(vetor) - 1:
- insertion_sort_recursivo(vetor, indice + 1)
- return vetor
+ if index < len(vector) - 1:
+ insertion_sort_recursive(vector, index + 1)
+ return vector
if __name__ == "__main__":
- lista_nao_ordenada = [8, 1, 3, 5, 7, 9, 0, 2, 4, 6]
- print("Lista não ordenada:")
- print(lista_nao_ordenada)
+ list1 = [8, 1, 3, 5, 7, 9, 0, 2, 4, 6]
+ print("Unsorted list: ")
+ print(list1)
- lista_nao_ordenada = insertion_sort_iterativo(lista_nao_ordenada)
- print("Lista ordenada com insertion sort iterativo:")
- print(lista_nao_ordenada)
+ list1 = insertion_sort_iterative(list1)
+ print("Sorted list with iterative insertion sort: ")
+ print(list1)
- lista_nao_ordenada = insertion_sort_recursivo(lista_nao_ordenada, 1)
- print("Lista ordenada com insertion sort recursivo:")
- print(lista_nao_ordenada)
+ list2 = [8, 1, 3, 5, 7, 9, 0, 2, 4, 6]
+ print("Unsorted list: ")
+ print(list2)
+
+ list2 = insertion_sort_recursive(list2, 1)
+ print("Sorted list with recursive insertion sort: ")
+ print(list2)
diff --git a/src/python/linear_search_recursive.py b/src/python/linear_search_recursive.py
index f164b299..01efd74b 100644
--- a/src/python/linear_search_recursive.py
+++ b/src/python/linear_search_recursive.py
@@ -1,4 +1,3 @@
-""" Implementaçao do algoritmo de busca sequencial com recursão """
"""Implementation of the sequential search algorithm with recursion."""
diff --git a/src/python/lz77.py b/src/python/lz77.py
index 249444f4..fba93b12 100644
--- a/src/python/lz77.py
+++ b/src/python/lz77.py
@@ -1,4 +1,3 @@
-import io
import sys
diff --git a/src/python/queue.py b/src/python/queue.py
index 791d78a6..1730f820 100644
--- a/src/python/queue.py
+++ b/src/python/queue.py
@@ -1,34 +1,88 @@
-""" Implementação da estrutura de dados "fila" """
+class Node:
+ def __init__(self, value):
+ self.value = value
+ self.left_ptr = None
-import random
+ @property
+ def prev(self):
+ return self.left_ptr
+
+ @prev.setter
+ def prev(self, ptr):
+ self.left_ptr = ptr
+
+ @property
+ def get_value(self):
+ return self.value
class Queue:
def __init__(self):
- self.__queue = []
+ self.head = None
+ self.tail = None
+ self.length = 0
def enqueue(self, value):
- self.__queue.append(value)
+ new = Node(value)
+ self.length += 1
+ # if empty make new node both head and tail of queue
+ if self.head is None:
+ self.head = new
+ self.tail = new
+ # otherwise add new node to end of queue and update tail
+ else:
+ self.tail.prev = new
+ self.tail = new
def dequeue(self):
- return self.__queue.pop(0)
+ if self.length == 0:
+ print("Queue is empty, cannot dequeue")
+ return
+ else:
+ tmp = self.head
+ self.head = self.head.prev
+ self.length -= 1
+ return tmp.get_value
def show(self):
- print(f"Queue: {self.__queue}")
+ # first element is the head of the queue
+ ptr = self.head
+ val = []
+ while ptr is not None:
+ val.append(ptr.get_value)
+ ptr = ptr.prev
+
+ print(val)
+
+ def length(self):
+ return self.length
def main():
queue = Queue()
- for _ in range(0, 10):
- queue.enqueue(random.randint(10, 99))
+ print("Queuing 1 and 7")
+ queue.enqueue(1)
+ queue.show()
+ print(f"Queue is length {queue.length}")
+ queue.enqueue(7)
+ queue.show()
+ print(f"Queue is length {queue.length}")
+ print(f"Dequeuing {queue.dequeue()}")
+ queue.show()
+ print(f"Queue is length {queue.length}")
+ print(f"Dequeuing {queue.dequeue()}")
queue.show()
+ print(f"Queue is length {queue.length}")
- queue.dequeue()
- queue.dequeue()
+ print(f"Dequeuing {queue.dequeue()}")
+ print(f"Queue is length {queue.length}")
+ print("Queueing 12")
+ queue.enqueue(12)
queue.show()
+ print(f"Queue is length {queue.length}")
if __name__ == "__main__":
diff --git a/src/python/quick_sort.py b/src/python/quick_sort.py
index 7c1dd5bd..a1015cdd 100644
--- a/src/python/quick_sort.py
+++ b/src/python/quick_sort.py
@@ -1,15 +1,15 @@
-""" Implementaçao do algoritmo quick sort """
+""" Quick Sort in Python """
def swap(a_list, pos1, pos2):
- """Troca a posição de dois itens em uma lista"""
+ """Swaps the position of two items in a list"""
temp = a_list[pos1]
a_list[pos1] = a_list[pos2]
a_list[pos2] = temp
def partition(a_list, start, end):
- """Divide uma lista"""
+ """Splits a list"""
pivot = a_list[start]
while True:
while a_list[start] < pivot:
@@ -28,7 +28,7 @@ def partition(a_list, start, end):
def quick_sort(a_list, start, end):
- """Algoritmo de quick sort"""
+ """Quick sort algorithm"""
if start < end:
part = partition(a_list, start, end)
quick_sort(a_list, start, part)
diff --git a/src/python/radix_sort.py b/src/python/radix_sort.py
new file mode 100644
index 00000000..fc91c414
--- /dev/null
+++ b/src/python/radix_sort.py
@@ -0,0 +1,55 @@
+import random
+
+
+def radix_sort(arr):
+ # Find the maximum number to know the number of digits
+ max_num = max(arr)
+
+ # Do counting sort for every digit, starting from the least significant digit
+ exp = 1
+ while max_num // exp > 0:
+ counting_sort(arr, exp)
+ exp *= 10
+
+
+def counting_sort(arr, exp):
+ n = len(arr)
+ output = [0] * n
+ count = [0] * 10
+
+ for i in range(n):
+ index = arr[i] // exp
+ count[index % 10] += 1
+
+ for i in range(1, 10):
+ count[i] += count[i - 1]
+
+ i = n - 1
+ while i >= 0:
+ index = arr[i] // exp
+ output[count[index % 10] - 1] = arr[i]
+ count[index % 10] -= 1
+ i -= 1
+
+ for i in range(n):
+ arr[i] = output[i]
+
+
+def main():
+ print("Fixed Testing Array")
+ arr = [170, 2, 45, 75, 75, 90, 802, 24, 2, 66]
+ print("Unsorted array:", arr)
+ radix_sort(arr)
+ print("Sorted array:", arr)
+
+ print("Random Testing Array")
+ arr = []
+ for i in range(0, 10):
+ arr.append(random.randint(0, 20))
+ print("Unsorted array:", arr)
+ radix_sort(arr)
+ print("Sorted array:", arr)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/python/singly_linked_list.py b/src/python/singly_linked_list.py
index fed7cf5c..482d3037 100644
--- a/src/python/singly_linked_list.py
+++ b/src/python/singly_linked_list.py
@@ -1,8 +1,5 @@
"""
-!/usr/bin/env python
--*- coding: utf-8 -*-
-
-Lista Ligada:
+Linked List:
_________ _________ _________ _________
head --> | 2 | --|--> | 1 | --|--> | 5 | --|--> | 3 | --|--> None
--------- --------- --------- ---------
diff --git a/src/python/skip_list.py b/src/python/skip_list.py
new file mode 100644
index 00000000..1632a33f
--- /dev/null
+++ b/src/python/skip_list.py
@@ -0,0 +1,471 @@
+"""
+Skip list with:
+ - skip connections made at random
+ - sorted order
+ - removing a node leaves a pseudo dead node
+ - automatically rebuilds with only alive nodes once half of nodes are dead
+ - can be rebuilt whenever desired as well
+ - does not allow for duplicate numbers
+
+"""
+
+import random
+
+
+class Node:
+ def __init__(self, value):
+ self.value = value
+ self._down = None
+
+ # layer number, 1 if on bottom layer
+ self._layer = None
+ self._right = None
+
+ self._isAlive = True
+
+ @property
+ def status(self):
+ return self._isAlive
+
+ @property
+ def kill(self):
+ self._isAlive = False
+
+ @property
+ def next(self):
+ return self._right
+
+ @next.setter
+ def next(self, ptr):
+ self._right = ptr
+
+ @property
+ def get_value(self):
+ return self.value
+
+ @property
+ def layer(self):
+ return self._layer
+
+ @layer.setter
+ def layer(self, val):
+ self._layer = val
+
+ @property
+ def down(self):
+ return self._down
+
+ @down.setter
+ def down(self, ptr):
+ self._down = ptr
+
+
+class Skip_List:
+ def __init__(self) -> None:
+ self.head = None
+
+ # current height of skip list
+ self.height = 1
+
+ # these counts do not consider duplicate elements for skip connections
+ self.size = 0 # number of elements, alive or dead
+ self.num_alive = 0 # number of living elements
+ self.num_dead = 0 # number of dead elements
+
+ def reset(self):
+ # reinitialize values
+ self.head = None
+ self.height = 1
+ self.size = 0
+ self.num_alive = 0
+ self.num_dead = 0
+
+ def status(self):
+ print(
+ f"There are {self.size} element(s) in the skip list, of which "
+ f"{self.num_alive} are alive and {self.num_dead} are dead"
+ )
+ print(f"The list has {self.height} layers")
+
+ def insert(self, value):
+ new = Node(value)
+ # if empty
+ if self.size == 0:
+ # make new node the head
+ self.head = new
+ new.layer = 1
+
+ # if new value is less than head
+ elif value < self.head.get_value:
+ # update head
+ tmp = self.head
+ self.head = new
+ new.layer = tmp.layer
+ new.next = tmp
+ # create skip layers of new head
+ i = tmp.layer
+ if i > 1:
+ curr = tmp.down
+ prev_new = new
+ curr_new = Node(value)
+ curr_new.layer = curr.layer
+ while i > 1:
+ prev_new.down = curr_new
+ curr_new.next = curr
+ curr_new.layer = curr.layer
+
+ curr = curr.down
+ prev_new = curr_new
+ curr_new = Node(value)
+
+ i -= 1
+ else:
+ curr = self.head
+ while True:
+ # move to the right if possible
+ if curr.next is not None:
+ # move to the right if next value is still smaller
+ if curr.next.get_value < value:
+ curr = curr.next
+ # element already exists in the list
+ elif curr.next.get_value == value:
+ print("This value is already in the list")
+ return
+ # if next value is larger you can move down a level
+ elif curr.down is not None:
+ curr = curr.down
+ # otherwise you have found your spot
+ else:
+ tmp = curr.next
+ curr.next = new
+ new.layer = 1
+ new.next = tmp
+ break
+ # move down if you cannot move right
+ elif curr.down is not None:
+ curr = curr.down
+ # otherwise you have reached the end of the list
+ else:
+ curr.next = new
+ new.layer = 1
+ break
+
+ # coin flips to see if new element gets skip connections
+ coin = random.randint(0, 1)
+ if coin:
+ new_layer = 2
+ prev_new = new
+
+ while coin:
+ print(f"Skip connection added on {new_layer}!")
+ curr_new = Node(value)
+
+ # if adding to skip list height
+ if new_layer > self.height:
+ # update head
+ new_head = Node(self.head.get_value)
+ new_head.layer = new_layer
+ new_head.down = self.head
+ self.head = new_head
+ self.height += 1
+
+ curr = self.head
+
+ # start at head and move down to layer that gets new skip connection
+ while curr.layer != new_layer:
+ curr = curr.down
+
+ # move along layer new connection is being added
+ while True:
+ # found spot at end of skip connections
+ if curr.next is None:
+ # insert
+ curr.next = curr_new
+ curr_new.layer = new_layer
+
+ # update curr_new values
+ curr_new.down = prev_new
+
+ # update previous new
+ prev_new = curr_new
+ break
+ # keep moving to the right
+ elif curr.next.get_value < value:
+ curr = curr.next
+ # found skip connection location between values
+ else:
+ # insert between
+ tmp = curr.next
+ curr.next = curr_new
+ curr_new.next = tmp
+
+ # update new node values
+ curr_new.layer = new_layer
+ curr_new.down = prev_new
+
+ # update previous new
+ prev_new = curr_new
+ break
+
+ # flip another coin and increase list level
+ coin = random.randint(0, 1)
+ new_layer += 1
+
+ # update skip list values
+ self.size += 1
+ self.num_alive += 1
+
+ def find(self, value):
+ """
+ returns a pointer to the highest element in skip list with this value
+ if it is alive and exists,
+ otherwise returns none and not considered to be in the list
+
+ """
+ curr = self.head
+ if curr.get_value == value:
+ print(f"{value} is in the list")
+ return curr
+
+ while True:
+ # if you can move right
+ if curr.next is not None:
+ # keep moving right if value not found yet and if it can still be in the list
+ if curr.next.get_value < value:
+ curr = curr.next
+ # if the next value is what you are looking
+ elif curr.next.get_value == value:
+ # check if it is a living node
+ if curr.next.status:
+ print(f"{value} is in the list")
+ return curr.next
+ else:
+ print(f"{value} is not in the list")
+ return None
+ elif curr.down is None:
+ # no need to keep looking all other values are larger and cant go down
+ print(f"{value} is not in the list")
+ return None
+ else:
+ curr = curr.down
+ # move down if you cant move right
+ elif curr.down is not None:
+ curr = curr.down
+ # no where else to go! end of the list
+ else:
+ print(f"{value} is not in the list")
+ return None
+
+ def remove(self, value):
+ """
+ psuedo deletes an element with a value of value if it exists
+ """
+ curr = self.find(value)
+
+ # remove highest occurance of this element
+ if curr is not None:
+ print(f"{value} was removed from the list")
+ self.num_dead += 1
+ self.num_alive -= 1
+ i = curr.layer
+ curr.kill
+ # remove all other occurances of this element
+ while i > 1:
+ curr = curr.down
+ curr.kill
+ i = curr.layer
+
+ # check if rebuild is needed
+ if self.num_dead / self.size > 0.5:
+ self.rebuild()
+
+ else:
+ print(f"{value} was not in the list")
+
+ def show_layers(self, show_type="alive"):
+ """
+ prints out each layer of the skip list
+
+ show_type
+ - 'both' will print out both alive and dead elements
+ - 'alive' will only print alive elements
+ - 'dead' will only print dead elements
+ - treats anything else as 'both'
+ """
+ if self.size == 0:
+ print("The list is empty")
+ return
+
+ if show_type == "alive":
+ print("List contains these living nodes at the following Layers:")
+ elif show_type == "dead":
+ print("List contains these dead nodes at the following Layers:")
+ else:
+ print("List contains these living and dead nodes at the following Layers:")
+
+ # for each layer
+ for curr_layer in range(self.height, 0, -1):
+ curr = self.head
+ vals = [] # values in this layer
+ # move down to layer curr_layer
+ while curr.layer != curr_layer:
+ curr = curr.down
+
+ # add elements until reaching end of this layer
+ while curr is not None:
+ if show_type == "alive":
+ if curr.status:
+ vals.append(curr.get_value)
+ elif show_type == "dead":
+ if not curr.status:
+ vals.append(curr.get_value)
+ else:
+ vals.append(curr.get_value)
+
+ curr = curr.next
+
+ print(f"\tLayer {curr_layer}: {vals}")
+
+ def rebuild(self):
+ """
+ rebuild the data structure with only the alive nodes
+ """
+
+ print("\n\n\nRebuilding Skip List!\n\n\n")
+ vals = []
+
+ # find values of all living nodes
+ curr = self.head
+
+ # move to layer 1
+ while curr.layer != 1:
+ curr = curr.down
+
+ # traverse list adding values of living elements
+ while curr is not None:
+ if curr.status:
+ vals.append(curr.get_value)
+ curr = curr.next
+
+ # reinitalize values of skip list
+ self.reset()
+
+ for val in vals:
+ self.insert(val)
+
+
+def main():
+ L = Skip_List()
+
+ # testing first insert
+ print("\n\n-------- Inserting 3 --------")
+ L.insert(3)
+ L.status()
+ L.show_layers()
+ L.show_layers("dead")
+ L.show_layers("both")
+
+ # testing second insert
+ print("\n\n-------- Inserting 4 --------")
+ L.insert(4)
+ L.status()
+ L.show_layers()
+ L.show_layers("dead")
+ L.show_layers("both")
+
+ # testing insert of new minimum
+ print("\n\n-------- Inserting 1 --------")
+ L.insert(1)
+ L.status()
+ L.show_layers()
+ L.show_layers("dead")
+ L.show_layers("both")
+
+ # testing duplicate insert
+ print("\n\n-------- Inserting Duplicate 3 --------")
+ L.insert(3)
+ L.status()
+ L.show_layers()
+ L.show_layers("dead")
+ L.show_layers("both")
+
+ # testing removal
+ print("\n\n-------- Removing 3 --------")
+ L.remove(3)
+ L.status()
+ L.show_layers()
+ L.show_layers("dead")
+ L.show_layers("both")
+
+ # testing removal of non living element
+ print("\n\n-------- Removing 3 Again--------")
+ L.remove(3)
+ L.status()
+ L.show_layers()
+ L.show_layers("dead")
+ L.show_layers("both")
+
+ # testing removal of element not in list at all
+ print("\n\n-------- Removing 5 (was never inserted) --------")
+ L.remove(5)
+ L.status()
+ L.show_layers()
+ L.show_layers("dead")
+ L.show_layers("both")
+
+ # testing removal to empty and rebuilding
+ print("\n\n-------- Removing Until Empty --------")
+ L.remove(1)
+ L.status()
+ L.show_layers()
+ L.show_layers("dead")
+ L.show_layers("both")
+
+ L.remove(4)
+ L.status()
+ L.show_layers()
+ L.show_layers("dead")
+ L.show_layers("both")
+
+ # testing arbitrary inserts
+ print("\n\n------------ Arbitrary Inserts ------------\n\n")
+ vals = []
+ for i in range(0, 50):
+ val = random.randint(0, 100)
+ print(f"\n\n---Inserting {val}---")
+ vals.append(val)
+ L.insert(val)
+
+ L.status()
+ L.show_layers()
+ L.show_layers("dead")
+ L.show_layers("both")
+
+ # testing arbitrary removals
+ print("\n\n------------ Arbitrary Removals ------------\n\n")
+ for i in range(0, 30):
+ idx = random.randint(0, len(vals) - 1)
+ val = vals.pop(idx)
+ print(f"\n\n---Removing {val}---")
+ L.remove(val)
+
+ L.status()
+ L.show_layers()
+ L.show_layers("dead")
+ L.show_layers("both")
+
+ # testing arbitary removal of number not in list (dead or alive)
+ print("\n\n------------ Arbitrary Non-Existant Removals ------------\n\n")
+ for i in range(0, 10):
+ val = random.randint(100, 200)
+ print(f"\n\n---Removing {val}---")
+ L.remove(val)
+
+ L.status()
+ L.show_layers()
+ L.show_layers("dead")
+ L.show_layers("both")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/python/unordered_linked_list.py b/src/python/unordered_linked_list.py
new file mode 100644
index 00000000..230547ed
--- /dev/null
+++ b/src/python/unordered_linked_list.py
@@ -0,0 +1,113 @@
+class Node:
+ def __init__(self, value, rptr=None) -> None:
+ self.value = value
+ self.rptr = rptr
+
+ @property
+ def get_value(self):
+ return self.value
+
+ @property
+ def next(self):
+ return self.rptr
+
+ @next.setter
+ def next(self, ptr):
+ self.rptr = ptr
+
+
+class Unordered_Linked_List:
+ def __init__(self) -> None:
+ self.first_node = None
+
+ def insert(self, value):
+ # inserts a new node with the given value
+ if self.first_node is None:
+ self.first_node = Node(value)
+ else:
+ tmp = Node(value)
+ tmp.next = self.first_node
+ self.first_node = tmp
+
+ def find(self, value):
+ # returns true if the specified value is in your list
+ ptr = self.first_node
+ while ptr is not None:
+ if ptr.value == value:
+ print(f"{value} is in your list")
+ return True
+ else:
+ ptr = ptr.next
+
+ print(f"{value} is not in your list")
+ return False
+
+ def size(self): # returns size of the list
+ ptr = self.first_node
+ i = 0
+ while ptr is not None:
+ ptr = ptr.next
+ i += 1
+ print(f"Your list is of size {i}")
+ return i
+
+ def remove(self, value):
+ # removes all instances of a given value
+ ptr = self.first_node
+ prev = None
+ while ptr is not None:
+ if ptr.value == value:
+ if ptr == self.first_node:
+ tmp = ptr.next
+ self.first_node = tmp
+ else:
+ prev.next = ptr.next
+
+ prev = ptr
+ ptr = ptr.next
+
+ def show(self):
+ ptr = self.first_node
+ val = []
+ while ptr is not None:
+ val.append(ptr.get_value)
+ ptr = ptr.next
+
+ print(val)
+
+
+def main():
+ list = Unordered_Linked_List()
+
+ list.insert(1)
+ list.insert(3)
+ list.insert(5)
+ list.insert(2)
+
+ list.size()
+ list.show()
+
+ list.find(3)
+ list.find(9)
+
+ list.remove(1)
+ list.remove(3)
+ list.remove(5)
+ list.remove(2)
+
+ list.show()
+
+ list.insert(1)
+ list.insert(3)
+ list.insert(5)
+ list.insert(3)
+
+ list.show()
+
+ list.remove(3)
+
+ list.show()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/scala/BinarySearch.scala b/src/scala/BinarySearch.scala
new file mode 100644
index 00000000..2088863d
--- /dev/null
+++ b/src/scala/BinarySearch.scala
@@ -0,0 +1,26 @@
+import scala.annotation.tailrec
+
+def binarySearch(data: Seq[Int], target: Int): Option[Int] = {
+
+ @tailrec
+ def search(left: Int, right: Int): Option[Int] = {
+ if (left > right) {
+ None
+ } else {
+ val middle: Int = (left + right) / 2
+ if (data(middle) == target) Some(middle)
+ else if (data(middle) < target) search(middle + 1, right)
+ else search(left, middle - 1)
+ }
+ }
+
+ search(0, data.size)
+}
+
+object Main extends App {
+ val data: Seq[Int] = Seq(0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12)
+ val value: Int = 11
+ println(
+ s"Value '$value' found in position '${binarySearch(data, value).get}'"
+ )
+}
diff --git a/src/scala/Bogosort.scala b/src/scala/Bogosort.scala
new file mode 100644
index 00000000..8a390de8
--- /dev/null
+++ b/src/scala/Bogosort.scala
@@ -0,0 +1,22 @@
+import scala.annotation.tailrec
+import scala.util.Random
+
+@tailrec
+def isSorted(data: Seq[Int]): Boolean = {
+ if (data.size < 2) true
+ else if (data(0) > data(1)) false
+ else isSorted(data.tail)
+}
+
+@tailrec
+def bogosort(data: Seq[Int]): Seq[Int] = {
+ val result: Seq[Int] = Random.shuffle(data)
+ if (isSorted(result)) result
+ else bogosort(data)
+}
+
+object Main extends App {
+ val data: Seq[Int] = Seq.fill(10)(Random.nextInt(10))
+ println(s"Unsorted data: $data")
+ println(s"Sorted data: ${bogosort(data)}")
+}
diff --git a/src/scala/Exponentiation.scala b/src/scala/Exponentiation.scala
new file mode 100644
index 00000000..0640a121
--- /dev/null
+++ b/src/scala/Exponentiation.scala
@@ -0,0 +1,9 @@
+def exponentiation(base: Int, exponent: Int): Int = {
+ (1 to exponent)
+ .map(_ => base)
+ .reduce(_ * _)
+}
+
+object Main extends App {
+ println("5 ^ 3 = " + exponentiation(5, 3))
+}
diff --git a/src/scala/ExponentiationRecursive.scala b/src/scala/ExponentiationRecursive.scala
new file mode 100644
index 00000000..58f31682
--- /dev/null
+++ b/src/scala/ExponentiationRecursive.scala
@@ -0,0 +1,15 @@
+import scala.annotation.tailrec
+
+@tailrec
+def exponentiationRecursive(
+ base: Int,
+ exponent: Int,
+ accumulator: Int = 1
+): Int = exponent match {
+ case 0 => accumulator
+ case _ => exponentiationRecursive(base, exponent - 1, accumulator * base)
+}
+
+object Main extends App {
+ println("5 ^ 3 = " + exponentiationRecursive(5, 3))
+}
diff --git a/src/scala/Palindrome.scala b/src/scala/Palindrome.scala
new file mode 100644
index 00000000..b8b80bb3
--- /dev/null
+++ b/src/scala/Palindrome.scala
@@ -0,0 +1,15 @@
+def isPalindrome(content: String): Boolean = {
+ val sanitizedContent: String = content.replaceAll("\\W", "").toLowerCase
+ sanitizedContent == sanitizedContent.reverse
+}
+
+object Main extends App {
+ val data: Seq[String] = Seq(
+ "",
+ "a",
+ "abba",
+ "No lemon, no melon",
+ "Was it a palindrome?"
+ )
+ data.foreach(x => println(s"'$x' is a palindrome? ${isPalindrome(x)}"))
+}
|