From f0f9aeea6f2ca3ca483fce2ce38dfbc3103e327c Mon Sep 17 00:00:00 2001 From: DavdaJames Date: Sat, 19 Oct 2024 05:10:37 +0530 Subject: [PATCH] added the english comments and also the code conversion into english commented so that just required to uncomment to run the english code --- src/c/BinarySearchTree.c | 214 +++++++++++++++++++++++- src/c/BinaryTree.c | 208 ++++++++++++++++++++++- src/c/BubbleSort.c | 6 +- src/c/CalculatePi.c | 33 +++- src/c/CircularLinkedList.c | 109 +++++++++++- src/c/ConnectedComponents.c | 74 ++++++++- src/c/CountingSort.c | 81 +++++++++ src/c/Dijkstra.c | 100 +++++++++++ src/c/DoublyLinkedList.c | 146 ++++++++++++++++ src/c/DynamicQueue.c | 79 ++++++++- src/c/DynamicStack.c | 88 +++++++++- src/c/Exponentiation.c | 21 +++ src/c/ExponentiationRecursive.c | 18 ++ src/c/Factorial.c | 33 ++++ src/c/FactorialRecursive.c | 19 +++ src/c/FloydWarshall.c | 92 ++++++++++- src/c/GraphSearch.c | 205 ++++++++++++++++++++++- src/c/Graphs.c | 139 +++++++++++++++- src/c/HamiltonianCycle.c | 153 ++++++++++++++++- src/c/InsertionSort.c | 48 +++++- src/c/LinearSearch.c | 20 +++ src/c/LinearSearchRecursive.c | 27 +++ src/c/LinearSearchSentinel.c | 46 ++++++ src/c/MaxRecursive.c | 72 ++++++++ src/c/MergeSort.c | 73 +++++++- src/c/MinMaxRecursive.c | 2 + src/c/Palindrome.c | 41 +++++ src/c/Queue.c | 93 ++++++++++- src/c/QuickSort.c | 103 +++++++++++- src/c/SinglyLinkedList.c | 285 ++++++++++++++++++++++++++++++++ src/c/SortedLinkedList.c | 109 +++++++++++- src/c/Stack.c | 89 +++++++++- src/c/TravellingSalesman.c | 110 +++++++++++- src/c/UnorderedLinkedList.c | 93 ++++++++++- 34 files changed, 3009 insertions(+), 20 deletions(-) diff --git a/src/c/BinarySearchTree.c b/src/c/BinarySearchTree.c index e29bb525..5335fa7d 100644 --- a/src/c/BinarySearchTree.c +++ b/src/c/BinarySearchTree.c @@ -204,4 +204,216 @@ int main(){ printf("\nAltura: %d\n", altura(noArvore) ); return 0; -} \ No newline at end of file +} + + + + + + + + +// IN english +/* +* Binary Search Tree in C +* +* ( 6 ) +* / \ +* ( 2 ) ( 7 ) +* / \ \ +* ( 1 ) ( 4 ) ( 8 ) +* / \ +* ( 3 ) ( 5 ) +*/ +// typedef int KEYTYPE; + +// typedef struct AUX{ +// KEYTYPE key; +// struct AUX *left, *right; +// }NODE, *PTR; // NODE is the structure, and PTR is a pointer to NODE + +// int max(int a, int b){ +// if( a > b ) +// return a; +// return b; +// } + +// int height(PTR node){ +// if( node == NULL ) // Same as using if(!node) +// return 0; +// return 1 + max( height(node->left), height(node->right) ); // Traverses the tree from left and right to check which one has a greater height +// } + +// PTR binarySearch(KEYTYPE key, PTR root){ +// if( !root ) +// return NULL; +// if( root->key == key ) +// return root; +// if( root->key < key ) +// binarySearch(key, root->right); +// else +// binarySearch(key, root->left); +// } + +// PTR linearBinarySearch(KEYTYPE key, PTR current){ +// while( current != NULL ){ +// if( current->key == key ) +// return current; +// if( current->key < key ) +// current = current->right; +// else +// current = current->left; +// } +// return NULL; +// } + +// PTR createNode(KEYTYPE key){ +// PTR node = (PTR) malloc( sizeof(NODE) ); +// node->left = NULL; +// node->right = NULL; +// node->key = key; +// return node; +// } + +// bool insert(KEYTYPE key, PTR current){ +// PTR previous; +// // Traverses the tree to the right or left until it finds a NULL (empty) position +// while(current != NULL){ +// previous = current; +// if( current->key < key ) +// current = current->right; +// else +// current = current->left; +// } +// current = createNode(key); // Uses the current variable, as it was "leftover" +// if( previous->key < key ) +// previous->right = current; +// else +// previous->left = current; +// return true; +// } + +// PTR searchParent(KEYTYPE key, PTR current){ +// PTR parent = current; +// while( current != NULL ){ +// if( current->key == key ) +// return parent; +// parent = current; +// if( current->key < key ) +// current = current->right; +// else +// current = current->left; +// } +// return parent; +// } + +// PTR largestOnLeft(PTR current){ +// current = current->left; +// while( current->right != NULL ) +// current = current->right; +// return current; +// } + +// bool deleteNode(KEYTYPE key, PTR root){ +// PTR current, parent, substitute, parentSubstitute; +// substitute = NULL; +// current = binarySearch(key, root); +// if( current == NULL ) return false; // Did not find the key +// parent = searchParent(key, root); +// if( current->left == NULL || current->right == NULL ){ // If it has 0 or 1 child +// if( current->left == NULL ) +// substitute = current->right; +// else +// substitute = current->left; +// if( parent == NULL ){ // The only one without a parent is the root +// root = substitute; +// }else{ +// if( key < parent->key) +// parent->left = substitute; +// else +// parent->right = substitute; +// } +// free(current); +// }else{ +// substitute = largestOnLeft(current); +// current->key = substitute->key; +// if( substitute->left != NULL ) +// current->left = substitute->left; +// else +// current->left = NULL; +// free(substitute); +// } +// return true; +// } + +// void preOrder(PTR node){ // Root - Left - Right +// if( !node ) return; +// printf("%d, ", node->key); +// preOrder(node->left); +// preOrder(node->right); +// } + +// void postOrder(PTR node){ // Left - Right - Root +// if( !node ) return; +// postOrder(node->left); +// postOrder(node->right); +// printf("%d, ", node->key); +// } + +// void inOrder(PTR node){ // Left - Root - Right +// if( !node ) return; +// inOrder(node->left); +// printf("%d, ", node->key); +// inOrder(node->right); +// } + +// // This function is not working +// bool recursiveInsert(KEYTYPE key, PTR node){ +// PTR previous; +// if( !node ){ +// node = createNode(key); +// }else{ +// previous = node; +// if( key < node->key ) +// recursiveInsert(key, node->left); +// else +// recursiveInsert(key, node->right); +// } +// if( previous->key < key ) +// previous->right = node; +// else +// previous->left = node; +// return true; +// } + +// int main(){ +// PTR treeRoot = createNode(6); + +// insert(2, treeRoot); +// insert(1, treeRoot); +// insert(4, treeRoot); +// insert(7, treeRoot); +// insert(8, treeRoot); +// insert(3, treeRoot); +// insert(5, treeRoot); + +// int searchedValue = 7; +// if( binarySearch(searchedValue, treeRoot) ) +// printf("Search: %d\n", binarySearch(searchedValue, treeRoot)->key ); +// else +// printf("Not found\n"); + +// deleteNode(4, treeRoot); + +// printf("Pre-order: "); +// preOrder(treeRoot); +// printf("\n"); +// printf("In-order: "); +// inOrder(treeRoot); +// printf("\n"); +// printf("Post-order: "); +// postOrder(treeRoot); + +// printf("\nHeight: %d\n", height(treeRoot) ); +// return 0; +// } diff --git a/src/c/BinaryTree.c b/src/c/BinaryTree.c index 1d7e5a51..fa393840 100644 --- a/src/c/BinaryTree.c +++ b/src/c/BinaryTree.c @@ -199,4 +199,210 @@ int main(void){ return 0; -} \ No newline at end of file +} + + + + + +// In english + +// This is an unbalanced binary tree. + +struct Node { + + int value; + struct Node* left; + struct Node* right; + int height; +}; + +int height(struct Node *n){ + + if(n == NULL) + return 0; + return n->height; +} + +int max(int a, int b){ + return (a > b) ? a : b; +} + +struct Node* newNode(int value){ + + struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); + + newNode->value = value; + newNode->left = NULL; + newNode->right = NULL; + newNode->height = 1; + + return newNode; +} + +struct Node* insert(struct Node* root, int value){ + + if(root == NULL){ + return newNode(value); + } + if(value <= root->value) { + root->left = insert(root->left, value); + } + else { + root->right = insert(root->right, value); + } + + root->height = 1 + max(height(root->left), height(root->right)); + + return root; +} + +int search(struct Node* root, int value){ + + if(root == NULL){ + printf(" Value [%d] not found.\n", value); + } + else if(root->value == value){ + printf(" Value [%d] found.\n", value); + } + else if(value <= root->value){ + return search(root->left, value); + } + else if(value >= root->value){ + return search(root->right, value); + } +} + +void preorder(struct Node* root){ + + if(root == NULL) return; + printf("[%d]", root->value); + preorder(root->left); + preorder(root->right); +} + +void inorder(struct Node* root){ + + if(root == NULL) return; + inorder(root->left); + printf("[%d]", root->value); + inorder(root->right); +} + +void postorder(struct Node* root){ + + if(root == NULL) return; + postorder(root->left); + postorder(root->right); + printf("[%d]", root->value); +} + +void levelOrder(struct Node* root, int level){ + + if(root == NULL){ + return; + } + if(level == 0){ + printf("[%d]", root->value); + } + else{ + levelOrder(root->left, level-1); + levelOrder(root->right, level-1); + } +} + +void printLevelOrder(struct Node* root){ + int h = height(root); + for(int i = 0; i < h; i++){ + levelOrder(root, i); + } +} + +struct Node* findMin(struct Node* root){ + struct Node* current = root; + while(current->left != NULL){ + current = current->left; + } + return current; +} + + +struct Node* deleteNode(struct Node* root, int value){ + + if(root == NULL){ + return root; + } + if(value < root->value) { + root->left = deleteNode(root->left, value); + } + else if(value > root->value){ + root->right = deleteNode(root->right, value); + } + else{ + if( (root->left == NULL) || (root->right == NULL) ){ + struct Node* temp = root->left ? root->left : root->right; + + if(temp == NULL){ + temp = root; + root = NULL; + } else{ + *root = *temp; + free(temp); + } + } + else{ + struct Node* temp = findMin(root->right); + root->value = temp->value; + root->right = deleteNode(root->right, temp->value); + } + } + + if(root == NULL){ + return root; + } + + root->height = 1 + max(height(root->left), height(root->right)); + + return root; +} + + +// int main(void){ + +// struct Node* root; +// root = insert(root, 10); +// root = insert(root, 2); +// root = insert(root, 33); +// root = insert(root, 4); +// root = insert(root, 57); +// root = insert(root, 6); +// root = insert(root, 12); + +// search(root, 33); +// search(root, 23); + +// printf("\n Preorder: "); +// preorder(root); + +// printf("\n Inorder: "); +// inorder(root); + +// printf("\n Postorder: "); +// postorder(root); + +// printf("\n Levelorder: "); +// printLevelOrder(root); + +// root = deleteNode(root, 7); + +// printf("\n Levelorder: "); +// printLevelOrder(root); + +// root = deleteNode(root, 6); + +// printf("\n Levelorder: "); +// printLevelOrder(root); + +// return 0; + +// } diff --git a/src/c/BubbleSort.c b/src/c/BubbleSort.c index 2b083c47..d50ab5a6 100644 --- a/src/c/BubbleSort.c +++ b/src/c/BubbleSort.c @@ -29,10 +29,14 @@ int main() bubble_sort(array, array_size); printf("Lista ordenada:\n"); + // printf("Sorted list:\n"); for (int i = 0; i < array_size - 1; i++) printf("%d, ", array[i]); printf("%d\n", array[array_size - 1]); return 0; -} \ No newline at end of file +} + + + diff --git a/src/c/CalculatePi.c b/src/c/CalculatePi.c index a66e63f9..779d1544 100644 --- a/src/c/CalculatePi.c +++ b/src/c/CalculatePi.c @@ -25,4 +25,35 @@ int main() printf("PI (%i): {%f}\n", n, leibniz_pi_calculation(n_terms[n])); return 0; -} \ No newline at end of file +} + + + + + +/* +Pi Calculation in C using the Leibniz series +*/ + +// float calculate_pi_leibniz(int num_terms) +// { +// float denominator = 1.0f; +// float sign = 1.0f; +// float pi = 0.0f; +// for (int i = 0; i < num_terms; i++) +// { +// pi += sign * (4.0 / denominator); +// denominator += 2.0; +// sign = sign * -1.0; +// } +// return pi; +// } + +// int main() +// { +// int term_counts[4] = {10, 1000, 100000, 10000000}; +// for (int n = 0; n < 4; n++) +// printf("PI with %i terms: %f\n", term_counts[n], calculate_pi_leibniz(term_counts[n])); + +// return 0; +// } diff --git a/src/c/CircularLinkedList.c b/src/c/CircularLinkedList.c index c1ebdfcc..daea1b0d 100644 --- a/src/c/CircularLinkedList.c +++ b/src/c/CircularLinkedList.c @@ -101,4 +101,111 @@ int main(){ printf("Valor %d não encontrado.\n", valor); return 0; -} \ No newline at end of file +} + + + +// In english + +/* +* +* Circular Ordered Linked List with Head Node (Dynamic Implementation) +* +*/ + + +// typedef int KeyType; // Type of ID for each node in the list + +// // Data structure representing each node in the list +// typedef struct Node { +// KeyType key; +// struct Node* next; +// } Node, *Pointer; + +// typedef struct { +// Pointer head; // Head node +// } List; + +// void initialize(List *list) { +// // Head node prevents the list from being empty and can also be used as a sentinel +// list->head = (Pointer) malloc(sizeof(Node)); +// list->head->next = list->head; // Initially points to itself since it is circular +// } + +// // This method does not alter the list, so a copy can be passed instead of a pointer +// Pointer sequential_search(KeyType key, List list, Pointer* previous) { +// *previous = list.head; // As it's a copy, dot (.) can be used instead of arrow (->), previous holds the pointer to the found node +// Pointer current = list.head->next; +// list.head->key = key; // Store the value in the head node to be used as a sentinel, it will be the last to be compared +// while (current->key != key) { +// *previous = current; // Store the pointer to the node +// current = current->next; // Move to the next node +// } +// if (current != list.head) // If the node is not the head node, it means it was found +// return current; // Return the node +// else +// return NULL; // If not found, return NULL +// } + +// bool delete_node(KeyType key, List *list) { +// Pointer current, previous; +// current = sequential_search(key, *list, &previous); // Search for the value to delete, previous is passed as an address, so the search function alters it +// if (current == NULL) return false; // Not found +// previous->next = current->next; // Previous node points to the next node (the one the node to be deleted points to) +// free(current); // Free the memory +// return true; +// } + +// void insert(KeyType key, List *list) { +// Pointer previous = list->head; // previous holds the pointer to the previous node +// Pointer current = list->head->next; // current holds the pointer to the current node + +// while (current->key < key && current != list->head) { +// previous = current; // Store the pointer to the current node, which will be the previous +// current = current->next; // Move to the next node +// } +// // When the correct position is found in ascending order +// Pointer new_node = (Pointer) malloc(sizeof(Node)); // Create a new node +// new_node->key = key; // Assign the key to the node +// new_node->next = current; // Point to the next node +// previous->next = new_node; // Previous node points to the new node +// } + +// Pointer display_list(List list) { +// Pointer current = list.head->next; // current receives the first element after the head node +// while (current != list.head) { // If it's not the head node, the list is not empty +// printf("[ %d ]->", current->key); // Display the value of the node +// current = current->next; // Move to the next node +// } +// printf("\n"); +// } + +// int main() { +// List list; +// initialize(&list); + +// insert(4, &list); +// insert(6, &list); +// insert(2, &list); +// insert(3, &list); +// insert(1, &list); +// insert(5, &list); + +// display_list(list); + +// delete_node(2, &list); +// delete_node(4, &list); +// delete_node(6, &list); + +// display_list(list); + +// // Example of searching the list +// Pointer found_node; +// int search_value = 2; +// if (sequential_search(search_value, list, &found_node) != NULL) +// printf("Value %d found.\n", search_value); +// else +// printf("Value %d not found.\n", search_value); + +// return 0; +// } diff --git a/src/c/ConnectedComponents.c b/src/c/ConnectedComponents.c index cc3a5507..ff76affb 100644 --- a/src/c/ConnectedComponents.c +++ b/src/c/ConnectedComponents.c @@ -65,4 +65,76 @@ int main(){ } return 0; -} \ No newline at end of file +} + + + + +/* +* +* Graphs - Algorithm to calculate the number of connected components in a given Graph +* +* GRAPH +* (0) (1)-------------(4)---------------(5) +* | | | | +* | | | | +* | | | | +* (2) (3)--------------- | +* | | +* ----------------------------------- +* +* +* Adjacency Matrix +* 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 Vertices +* 8 Edges +*/ + +// #define VERTICES 6 +// #define INF -1 + +// bool visited[VERTICES]; +// int componentCount = 0; + +// int adjacencyMatrix[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 that finds connected components from an adjacency matrix +// void calculateConnectedComponents(int current) { +// for (int i = 0; i < VERTICES; i++) { +// if (!visited[i] && adjacencyMatrix[current][i] == 1) { +// visited[i] = true; +// componentCount++; +// printf("(%d)-", i); +// calculateConnectedComponents(i); +// } +// } +// } + +// int main() { +// for (int i = 0; i < VERTICES; i++) +// visited[i] = false; + +// for (int i = 0; i < VERTICES; i++) +// if (!visited[i]) { +// componentCount = 0; +// calculateConnectedComponents(i); +// printf("\nNumber of connected components starting from vertex %d: %d\n\n", i, componentCount); +// } + +// return 0; +// } diff --git a/src/c/CountingSort.c b/src/c/CountingSort.c index 523fb7a4..47d6f2ff 100644 --- a/src/c/CountingSort.c +++ b/src/c/CountingSort.c @@ -59,3 +59,84 @@ int main() { return 0; } + + +// In english + +/* +* +* CountingSort - Counting Sort Algorithm +* Matheus Martins Batista - Universidade Federal de Itajuba - 2021 +* +*/ + +// Function to find the maximum element in the array +// int findMaxValue(int *array, int size) { +// int maxValue = array[0]; + +// // Iterate through the array to find the maximum value +// for (int i = 1; i < size; i++) { +// if (array[i] > maxValue) { +// maxValue = array[i]; // Update maxValue if current element is greater +// } +// } + +// return maxValue; // Return the maximum value found +// } + +// // Function to perform counting sort on arrayA and store the result in arrayB +// void countingSort(int *arrayA, int *arrayB, int size) { +// // Find the maximum value in arrayA to determine the size of the count array +// int maxValue = findMaxValue(arrayA, size); + +// // Allocate memory for the count array and initialize it to 0 +// int* countArray = calloc(maxValue + 1, sizeof(int)); + +// // Count the frequency of each element in arrayA +// for (int i = 0; i < size; i++) { +// countArray[arrayA[i]]++; +// } + +// // Compute the cumulative frequency +// for (int i = 1; i <= maxValue; i++) { +// countArray[i] += countArray[i - 1]; +// } + +// // Build the output array arrayB in sorted order +// for (int i = size - 1; i >= 0; i--) { +// arrayB[countArray[arrayA[i]] - 1] = arrayA[i]; +// countArray[arrayA[i]]--; // Decrement the count for the current element +// } + +// // Free the allocated memory for the count array +// free(countArray); +// } + +// int main() { +// int *arrayA, *arrayB; // Pointers for the input and output arrays +// int size = 10; // Size of the array +// arrayA = malloc(size * sizeof(int)); // Allocate memory for the input array +// arrayB = calloc(size, sizeof(int)); // Allocate memory for the output array + +// // Populate arrayA with random values +// srand(48 + size); +// for (int j = 0; j < size; j++) { +// arrayA[j] = rand() % 100; // Random values between 0 and 99 +// } + +// // Perform counting sort +// countingSort(arrayA, arrayB, size); + +// // Print the sorted output +// printf("Sorted array: "); +// for (int i = 0; i < size; i++) { +// printf("%d ", arrayB[i]); +// } +// printf("\n"); + +// // Free the allocated memory for the input and output arrays +// free(arrayA); +// free(arrayB); + +// return 0; +// } diff --git a/src/c/Dijkstra.c b/src/c/Dijkstra.c index 806ddbb2..57e49dd2 100644 --- a/src/c/Dijkstra.c +++ b/src/c/Dijkstra.c @@ -96,3 +96,103 @@ int main(){ return 0; } + +// In English +/* +* 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 +* +*/ + +// #define NUM_VERTICES 5 // 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 distanceMatrix[NUM_VERTICES][NUM_VERTICES], int numVertices) { +// bool visited[numVertices]; // Array to track visited vertices +// // Initialize visited vertices to false +// for (int i = 0; i < numVertices; i++) { +// visited[i] = false; +// } + +// // Start from the first vertex (0) +// for (int i = 1; i < numVertices; i++) { // Loop through each vertex +// int minIndex = -1; // Initialize the index of the minimum value +// unsigned long int minValue = 4294967295; // Start with "infinity" + +// // Find the unvisited vertex with the smallest distance +// for (int j = 1; j < numVertices; j++) { +// if (!visited[j] && distanceMatrix[j][0] < minValue) { +// minIndex = j; // Update the index of the minimum value +// minValue = distanceMatrix[j][0]; // Update the minimum value +// } +// } + +// visited[minIndex] = true; // Mark the vertex with the smallest distance as visited + +// // Update the distances for the neighboring vertices +// for (int j = 1; j < numVertices; j++) { +// // If a shorter path to j is found through minIndex +// if ((distanceMatrix[minIndex][0] + distanceMatrix[minIndex][j]) < distanceMatrix[j][0]) { +// distanceMatrix[j][0] = distanceMatrix[minIndex][0] + distanceMatrix[minIndex][j]; // Update distance +// } +// } +// } +// } + +// int main() { +// // Distance matrix representation of the graph +// unsigned long int distanceMatrix[NUM_VERTICES][NUM_VERTICES] = { +// {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(distanceMatrix, NUM_VERTICES); // Call Dijkstra's algorithm + +// printf("Total shortest path from vertex 0 to 4: %lu\n", distanceMatrix[4][0]); // Shortest total path + +// // Print the updated distance matrix +// printf("Updated Distance Matrix:\n"); +// for (int i = 0; i < NUM_VERTICES; ++i) { +// for (int j = 0; j < NUM_VERTICES; ++j) { +// if (distanceMatrix[i][j] < 10) +// printf(" %lu ", distanceMatrix[i][j]); // Print formatted distance +// else +// printf("%lu ", distanceMatrix[i][j]); // Print formatted distance +// } +// printf("\n"); +// } +// printf("\n"); + +// return 0; +// } diff --git a/src/c/DoublyLinkedList.c b/src/c/DoublyLinkedList.c index 1bf5cf3e..27f74404 100644 --- a/src/c/DoublyLinkedList.c +++ b/src/c/DoublyLinkedList.c @@ -155,3 +155,149 @@ int main() libera(p); return 0; } + + + +// In english + +/* +* Example of a Doubly Linked List in C +*/ + +// Doubly linked list node structure +// typedef struct Node { +// int data; // Data stored in the node +// struct Node *next; // Pointer to the next node +// struct Node *prev; // Pointer to the previous node +// } Node; + +// // Function to insert a new node at the beginning of the list +// void insertAtBeginning(int value, Node *head) { +// Node *newNode = malloc(sizeof(Node)); // Allocate memory for new node +// newNode->data = value; // Set the data for the new node +// newNode->next = head->next; // Point to the current first node + +// // Check if the list is not empty +// if (head->next != NULL) { +// head->next->prev = newNode; // Update the previous pointer of the current first node +// } + +// head->next = newNode; // Update the head to point to the new node +// newNode->prev = head; // Set the previous pointer of the new node to head +// } + +// // Function to insert a new node at the end of the list +// void insertAtEnd(int value, Node *head) { +// Node *newNode = malloc(sizeof(Node)); // Allocate memory for new node +// newNode->data = value; // Set the data for the new node +// newNode->next = NULL; // New node will be the last node + +// Node *current = head; // Start at the head +// while (current->next != NULL) { +// current = current->next; // Traverse to the last node +// } + +// current->next = newNode; // Link the last node to the new node +// newNode->prev = current; // Set the previous pointer of the new node +// } + +// // Function to search for a node with the specified value and remove it +// void searchAndRemove(int value, Node *head) { +// Node *current = head->next; // Start at the first node + +// while (current != NULL && current->data != value) { +// current = current->next; // Traverse the list +// } + +// if (current != NULL) { // Node found +// current->prev->next = current->next; // Bypass the current node +// if (current->next != NULL) { // If not the last node +// current->next->prev = current->prev; // Link the next node to the previous node +// } +// free(current); // Free memory of the removed node +// } else { +// printf("\nList does not contain the item\n\n"); +// system("pause"); +// } +// } + +// // Function to print the contents of the list +// void printList(Node *head) { +// Node *current; +// for (current = head->next; current != NULL; current = current->next) { +// printf("%d ", current->data); +// } +// } + +// // Function to display the main menu +// void displayMenu() { +// printf(" Main Menu\n"); +// printf("1 - Insert at beginning\n"); +// printf("2 - Insert at end\n"); +// printf("3 - Remove an item\n"); +// printf("4 - Exit\n"); +// printf("\nOption: "); +// } + +// // Function to free the allocated memory for the list +// void freeList(Node *head) { +// Node *current = head; +// while (current != NULL) { +// Node *nextNode = current->next; // Store the reference to the next node +// free(current); // Free memory of the current node +// current = nextNode; // Move to the next node +// } +// } + +// int main() { +// Node *head = malloc(sizeof(Node)); // Initialize the head of the list +// head->prev = NULL; +// head->next = NULL; + +// int option = 0, item; // Variables for menu option and item input + +// do { +// system("cls"); // Clear the screen +// printf("\nContents of the list: "); +// if (head->next != NULL) { +// printList(head); // Print the list if not empty +// } else { +// printf("List is EMPTY"); +// } +// printf("\n\n"); + +// displayMenu(); // Show menu options +// scanf("%d", &option); // Get user input for menu option +// switch (option) { +// case 1: +// printf("Insert at the beginning of the list: "); +// scanf("%d", &item); +// insertAtBeginning(item, head); // Insert at the beginning +// break; +// case 2: +// printf("Insert at the end of the list: "); +// scanf("%d", &item); +// insertAtEnd(item, head); // Insert at the end +// break; +// case 3: +// if (head->next != NULL) { +// printf("Remove an item: "); +// scanf("%d", &item); +// searchAndRemove(item, head); // Remove specified item +// } else { +// printf("\nList is EMPTY\n\n"); +// system("pause"); +// } +// break; +// case 4: +// break; +// default: +// printf("Invalid option!\n"); +// system("pause"); +// break; +// } +// } while (option != 4); // Continue until user chooses to exit + +// freeList(head); // Free the allocated memory for the list +// return 0; +// } diff --git a/src/c/DynamicQueue.c b/src/c/DynamicQueue.c index 5b1d3711..ecf1316d 100644 --- a/src/c/DynamicQueue.c +++ b/src/c/DynamicQueue.c @@ -69,4 +69,81 @@ int main(){ printf("Tamanho da fila: %d\n", tamanhoFila(fila) ); return 0; -} \ No newline at end of file +} + + + +/* +* Implementation of a Dynamic Linked Queue in C +*/ + +// typedef int KEYTYPE; // Define KEYTYPE as an integer + +// typedef struct NODE { +// KEYTYPE key; // The key/value of the node +// struct NODE* next; // Pointer to the next node +// }* POINTER; // Define POINTER as a pointer to a NODE + +// // Create a new node with the given key +// POINTER newNode(KEYTYPE ch) { +// POINTER aux = (POINTER) malloc(sizeof(NODE)); // Allocate memory for a new node +// aux->key = ch; // Set the key of the new node +// aux->next = NULL; // Initialize the next pointer to NULL +// return aux; // Return the new node +// } + +// // Insert a new node at the beginning of the queue +// POINTER insert(KEYTYPE ch, POINTER node) { +// POINTER aux = newNode(ch); // Create a new node +// aux->next = node; // Set the next pointer of the new node to the current node +// return aux; // Return the new head of the queue +// } + +// // Display the elements of the queue +// void showQueue(POINTER node) { +// while (node != NULL) { // Traverse the queue +// printf("[%d]->", node->key); // Print the key of the current node +// node = node->next; // Move to the next node +// } +// printf("NULL\n"); // Indicate the end of the queue +// } + +// // Remove the last node from the queue +// void remove(POINTER node) { +// POINTER prevNode = node; // Keep track of the previous node +// while (node->next != NULL) { // Traverse to the last node +// prevNode = node; // Update the previous node +// node = node->next; // Move to the next node +// } +// prevNode->next = NULL; // Disconnect the last node +// free(node); // Free memory of the last node +// } + +// // Calculate the size of the queue +// int queueSize(POINTER node) { +// int count = 0; // Initialize a counter +// while (node != NULL) { // Traverse the queue +// count++; // Increment the counter +// node = node->next; // Move to the next node +// } +// return count; // Return the size of the queue +// } + +// int main() { +// POINTER queue = newNode(5); // Initialize the queue with one element +// queue = insert(8, queue); // Insert new elements into the queue +// queue = insert(1, queue); +// queue = insert(3, queue); +// queue = insert(5, queue); +// queue = insert(4, queue); +// queue = insert(2, queue); + +// showQueue(queue); // Show the current state of the queue +// remove(queue); // Remove the last element +// showQueue(queue); // Show the queue again +// remove(queue); // Remove another element +// showQueue(queue); // Show the queue again + +// printf("Size of the queue: %d\n", queueSize(queue)); // Display the size of the queue +// return 0; +// } diff --git a/src/c/DynamicStack.c b/src/c/DynamicStack.c index f32a6dcd..504b8794 100644 --- a/src/c/DynamicStack.c +++ b/src/c/DynamicStack.c @@ -79,4 +79,90 @@ int main(){ printf("\nNão achou\n"); return 0; -} \ No newline at end of file +} + + + + + +/* +* Dynamic Stack using a Linked List in C +*/ + + +// #define ERROR -1 // Define a constant for error handling + +// typedef int KEYTYPE; // Define KEYTYPE as an integer + +// typedef struct NODE { +// KEYTYPE key; // The key/value of the node +// struct NODE *next; // Pointer to the next node +// }*STACK; // Define STACK as a pointer to a NODE + +// // Create a new stack with a given key +// STACK CREATE(KEYTYPE ch) { +// STACK newStack = (STACK) malloc(sizeof(STACK)); // Allocate memory for a new stack node +// newStack->key = ch; // Set the key of the new node +// newStack->next = NULL; // Initialize the next pointer to NULL +// return newStack; // Return the new stack node +// } + +// // Push a new key onto the stack +// STACK PUSH(KEYTYPE ch, STACK pi) { +// STACK new = CREATE(ch); // Create a new node +// new->next = pi; // Set the next pointer of the new node to the current top of the stack +// return new; // Return the new top of the stack +// } + +// // Pop the top element from the stack +// STACK POP(STACK pi) { +// STACK sub = pi->next; // Get the next element +// free(pi); // Free the memory of the top node +// return sub; // Return the new top of the stack +// } + +// // Show the elements in the stack +// void SHOW(STACK pi) { +// printf("STACK:\n"); +// while (pi->next != NULL) { // Traverse until the second-to-last element +// printf("[ %d ]\n", pi->key); // Print the key of the current node +// pi = pi->next; // Move to the next node +// } +// printf("[ %d ]\n", pi->key); // Print the last element +// } + +// // Search for a key in the stack +// bool SEARCH(KEYTYPE ch, STACK pi) { +// bool found = false; // Initialize found flag +// while (pi != NULL) { // Traverse the stack +// if (pi->key == ch) // Check if the current node's key matches +// found = true; // Set found flag to true +// pi = pi->next; // Move to the next node +// } +// return found; // Return the found status +// } + +// int main() { +// STACK vStack; // Declare a stack pointer + +// vStack = PUSH(1, vStack); // Push elements onto the stack +// vStack = PUSH(2, vStack); +// vStack = PUSH(3, vStack); +// vStack = PUSH(4, vStack); +// vStack = PUSH(5, vStack); +// vStack = PUSH(6, vStack); + +// SHOW(vStack); // Display the stack contents + +// vStack = POP(vStack); // Pop two elements from the stack +// vStack = POP(vStack); + +// SHOW(vStack); // Display the stack contents again + +// if (SEARCH(6, vStack)) // Search for a key in the stack +// printf("\nFound\n"); +// else +// printf("\nNot found\n"); + +// return 0; // Exit the program +// } diff --git a/src/c/Exponentiation.c b/src/c/Exponentiation.c index fb59d362..39239b5d 100644 --- a/src/c/Exponentiation.c +++ b/src/c/Exponentiation.c @@ -22,3 +22,24 @@ int main(){ return 0; } + + +// Function to calculate exponentiation (base raised to the power of exponent) +// int exponentiation(int base, int exponent) { +// int i; // Loop counter +// int result = base; // Initialize result with the base value + +// // Loop to multiply the base 'exponent - 1' times +// for (i = 0; i < exponent - 1; i++) { +// result *= base; // Multiply result by base +// } + +// return result; // Return the calculated exponentiation result +// } + +// int main() { +// // Call the exponentiation function with base 5 and exponent 3, and print the result +// printf("%d\n", exponentiation(5, 3)); + +// return 0; // Exit the program +// } \ No newline at end of file diff --git a/src/c/ExponentiationRecursive.c b/src/c/ExponentiationRecursive.c index c1214e2d..0246ba78 100644 --- a/src/c/ExponentiationRecursive.c +++ b/src/c/ExponentiationRecursive.c @@ -18,3 +18,21 @@ int main(){ return 0; } + + +// In english +// Function to calculate exponentiation using recursion +// int exponentiation(int base, int exponent) { +// // Base case: any number raised to the power of 0 is 1 +// if (exponent == 0) return 1; + +// // Recursive case: multiply the base by the result of exponentiation with decreased exponent +// return (base * exponentiation(base, exponent - 1)); +// } + +// int main() { +// // Call the exponentiation function with base 5 and exponent 3, and print the result +// printf("%d\n", exponentiation(5, 3)); + +// return 0; // Exit the program +// } \ No newline at end of file diff --git a/src/c/Factorial.c b/src/c/Factorial.c index 57dba9c7..c571736f 100644 --- a/src/c/Factorial.c +++ b/src/c/Factorial.c @@ -23,3 +23,36 @@ int fatorial(int num){ printf("%d * ", num); return num * fatorial(num - 1); } + + + + +// In english +/* +* Examples of a function to return the factorial of a number n +* This is a recursive function. +*/ + +// Function prototype for factorial +// int factorial(int num); + +// int main() { +// int num; // Variable to store the user input +// printf("Enter a number: "); // Prompt user for input +// scanf("%d", &num); // Read the user input + +// int result = factorial(num); // Call the factorial function +// printf("1 => "); +// printf("%d! is: %d\n", num, result); // Print the result + +// return 0; // Exit the program +// } + +// // Recursive function to calculate the factorial of a number +// int factorial(int num) { +// if (num <= 1) { // Base case: factorial of 0 or 1 is 1 +// return 1; +// } +// printf("%d * ", num); // Print the current number (for demonstration) +// return num * factorial(num - 1); // Recursive call +// } \ No newline at end of file diff --git a/src/c/FactorialRecursive.c b/src/c/FactorialRecursive.c index a2390927..eef0607e 100644 --- a/src/c/FactorialRecursive.c +++ b/src/c/FactorialRecursive.c @@ -18,3 +18,22 @@ int main(){ return 0; } + + +// In english + +// Function to calculate the factorial of a number n +// int factorial(int n) { +// // Base case: if n is 1, return 1 (1! = 1) +// if (n == 1) return 1; + +// // Recursive case: n! = n * (n-1)! +// return (n * factorial(n - 1)); +// } + +// int main() { +// // Call the factorial function with 5 and print the result +// printf("%d\n", factorial(5)); // Output: 120 + +// return 0; // Exit the program +// } \ No newline at end of file diff --git a/src/c/FloydWarshall.c b/src/c/FloydWarshall.c index b6c6b68c..ee9f58d0 100644 --- a/src/c/FloydWarshall.c +++ b/src/c/FloydWarshall.c @@ -82,4 +82,94 @@ int main(){ printf("\n\n"); return 0; -} \ No newline at end of file +} + + + +// In english + +/* +* Graphs - Floyd-Warshall Algorithm in C +* Complexity: Theta of vertices cubed = Theta(n^3) +* +* Finds the shortest path from all vertices to all vertices +* +* 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 +* +*/ + + +// #define nroVertices 5 // Defines a constant 5 which is the number of vertices in the graph + +// // The Floyd-Warshall algorithm receives the distance matrix and the number of vertices as parameters +// 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 the current path is greater than the path through vertex x, update the distance +// if (matriz[y][z] > (matriz[y][x] + matriz[x][z])) { +// matriz[y][z] = matriz[y][x] + matriz[x][z]; +// } +// } +// } +// } +// } + +// int main() { +// // Initialize the distance matrix with distances between vertices +// 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} +// }; + +// // Execute the Floyd-Warshall algorithm +// FloydWarshall(Matriz, nroVertices); + +// // Print the updated distance matrix +// printf("Matrix:\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"); + +// // Show all shortest paths +// printf("\n"); +// for (int i = 0; i < nroVertices; ++i) { +// for (int x = 0; x < nroVertices; ++x) { +// printf("Shortest distance from %d to %d = %lu.\n", i, x, Matriz[x][i]); +// } +// } +// printf("\n\n"); + +// return 0; +// } diff --git a/src/c/GraphSearch.c b/src/c/GraphSearch.c index 2bfe7708..d38d539c 100644 --- a/src/c/GraphSearch.c +++ b/src/c/GraphSearch.c @@ -200,4 +200,207 @@ int main(){ printf("BFS - Não encontrou.\n"); return 0; -} \ No newline at end of file +} + + +// In english + +/* +* +* Graphs - Implementation of an undirected graph structure in C +* Search Methods: Depth-First Search (DFS) and Breadth-First Search (BFS) +* +* +* (A)---------------(B)-------------(E)---------------(F) +* | | | | +* | | | | +* | | | | +* (C)---------------(D)--------------- | +* | | +* ----------------------------------- +* +* 6 Vertices +* 8 Edges +*/ + +// #define MAX_VERTICES 6 // MAXIMUM NUMBER OF VERTICES IN THE GRAPH; IF THE GRAPH IS CHANGED, THIS VARIABLE MUST ALSO BE CHANGED +// #define MAX_EDGES (MAX_VERTICES * (MAX_VERTICES - 1)) // CALCULATES THE MAXIMUM NUMBER OF EDGES THE GRAPH CAN HAVE + +// // Structure defining each vertex of the graph +// typedef struct NODE { +// char id; // Vertex identifier +// int numNeighbors; // Number of neighbors +// struct NODE* neighbors[MAX_EDGES]; // Array of neighbors +// bool visited; // Flag to indicate if the vertex has been visited +// } *VERTEX; + +// // Create vertex and return it +// VERTEX createVertex(char id) { +// VERTEX newVertex = (VERTEX) malloc(sizeof(NODE)); // Allocate a new vertex +// newVertex->id = id; // Set the vertex identifier +// newVertex->numNeighbors = 0; // Initialize the number of neighbors +// newVertex->visited = false; // Set the visited flag to false +// for (int i = 0; i < MAX_EDGES; i++) { +// newVertex->neighbors[i] = NULL; // Initialize the neighbors array +// } +// return newVertex; // Return the new vertex +// } + +// // Connect the specified vertices +// bool connectVertices(VERTEX v1, VERTEX v2) { +// int aux = 0; +// while (v1->neighbors[aux] != NULL) { // Find the first 'empty' (NULL) position among neighbors +// aux++; +// } +// v1->neighbors[aux] = v2; // Add the new neighbor to the list +// aux = 0; +// while (v2->neighbors[aux] != NULL) { // Find the first 'empty' (NULL) position among neighbors +// aux++; +// } +// v2->neighbors[aux] = v1; // Add the new neighbor to the list +// v1->numNeighbors++; // Increment the number of neighbors +// v2->numNeighbors++; // Increment the number of neighbors +// } + +// /* +// * Depth-First Search - DFS +// * Traverses all neighbors connected to the vertex first +// * +// */ +// int depthFirstSearch(VERTEX start, VERTEX target, int visited) { +// start->visited = true; // Mark the starting vertex as visited +// if (start == target) return visited; // If it's the target, return the count of visited vertices + +// int aux = 0; +// while (start->neighbors[aux] != NULL) { // While there are neighbors to visit +// if (start->neighbors[aux]->visited == false) { // If the neighbor hasn't been visited yet +// // Recursively call with the new neighbor as the start, traversing all its neighbors +// int response = depthFirstSearch(start->neighbors[aux], target, visited + 1); +// // If the return value is greater than -1, it means it found the target, so return the response +// if (response != -1) return response; +// } +// aux++; // Increment the index in the neighbors list +// } + +// return -1; // Target vertex not found +// } + +// /* +// * Breadth-First Search - BFS +// * Implemented using a simple array as a queue +// * It does not remove the vertex from the array; it simply skips to the next position +// * Traverses all vertices level by level +// */ +// int breadthFirstSearch(VERTEX start, VERTEX target) { +// int startQueue = 0; // Variable to control the start position of the queue, used in the WHILE loop +// int queueSize = 1; // Variable to control the size of the queue + +// VERTEX QUEUE[MAX_VERTICES]; // Queue that will hold vertices to be compared +// for (int i = 0; i < MAX_VERTICES; i++) { // Since the list is not dynamic, it needs to be cleared first +// QUEUE[i] = NULL; +// } +// QUEUE[startQueue] = start; // The first position of the queue receives the starting vertex + +// // While the queue is not empty +// while (startQueue < queueSize) { +// // If the vertex at the front of the queue is the target, return startQueue, the distance traveled +// if (QUEUE[startQueue] == target) return startQueue; + +// /* +// * For all neighbors of the vertex at the front of the queue: +// * Mark all as visited so they are not added to the queue again, +// * then add them to the queue and increase the size of the queue +// */ +// for (int i = 0; i < QUEUE[startQueue]->numNeighbors; i++) { +// if (QUEUE[startQueue]->neighbors[i]->visited == false) { +// QUEUE[startQueue]->neighbors[i]->visited = true; // Mark as visited +// QUEUE[queueSize] = QUEUE[startQueue]->neighbors[i]; // Add to the queue +// queueSize++; // Increment the queue size +// } +// } +// startQueue++; // Increment the start of the queue, simulating removal of the first element (FIFO) +// } +// return -1; // Target vertex not found +// } + +// int main() { +// // Graph consisting of independent 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'); + +// // Connect all vertices according to the graph presented in the introduction +// connectVertices(A, B); +// connectVertices(A, C); +// connectVertices(B, D); +// connectVertices(C, D); +// connectVertices(B, E); +// connectVertices(D, E); +// connectVertices(E, F); +// connectVertices(D, F); + +// // Perform depth-first search +// int res = depthFirstSearch(A, F, 0); +// if (res != -1) +// printf("DFS - Found. Distance: %d.\n", res); +// else +// printf("DFS - Not found.\n"); + +// // Reset all 'visited' attributes of all vertices to 'false' +// A->visited = false; +// B->visited = false; +// C->visited = false; +// D->visited = false; +// E->visited = false; +// F->visited = false; + +// // Perform breadth-first search +// res = breadthFirstSearch(A, F); +// if (res != -1) +// printf("BFS - Found. Distance: %d.\n", res); +// else +// printf("BFS - Not found.\n"); + +// // Graph consisting of vertices in an array +// VERTEX GRAPH[MAX_VERTICES]; +// GRAPH[0] = createVertex('A'); +// GRAPH[1] = createVertex('B'); +// GRAPH[2] = createVertex('C'); +// GRAPH[3] = createVertex('D'); +// GRAPH[4] = createVertex('E'); +// GRAPH[5] = createVertex('F'); + +// // Connect all vertices according to the graph presented in the introduction +// connectVertices(GRAPH[0], GRAPH[1]); +// connectVertices(GRAPH[0], GRAPH[2]); +// connectVertices(GRAPH[1], GRAPH[3]); +// connectVertices(GRAPH[2], GRAPH[3]); +// connectVertices(GRAPH[1], GRAPH[4]); +// connectVertices(GRAPH[3], GRAPH[4]); +// connectVertices(GRAPH[4], GRAPH[5]); +// connectVertices(GRAPH[3], GRAPH[5]); + +// // Perform depth-first search +// res = depthFirstSearch(GRAPH[0], GRAPH[5], 0); +// if (res != -1) +// printf("DFS - Found. Distance: %d.\n", res); +// else +// printf("DFS - Not found.\n"); + +// // Reset all 'visited' attributes of all vertices to 'false' +// for (int i = 0; i < MAX_VERTICES; i++) { +// GRAPH[i]->visited = false; +// } + +// // Perform breadth-first search +// res = breadthFirstSearch(GRAPH[0], GRAPH[5]); +// if (res != -1) +// printf("BFS - Found. Distance: %d.\n", res); +// else +// printf("BFS - Not found.\n"); + +// return 0; +// } diff --git a/src/c/Graphs.c b/src/c/Graphs.c index bd46e85a..37e79300 100644 --- a/src/c/Graphs.c +++ b/src/c/Graphs.c @@ -122,4 +122,141 @@ int main(){ mostraMatrizDistancia(); return 0; -} \ No newline at end of file +} + + + +// In English + +/* +* +* +* --------------------- +* | | +* | | +* 5 V 8 | +* (A)------------->(B)------------ | 2 +* \ | | +* \ | | +* \ 6 4 V | +* ---------->(C)--------->(D)------ +* +* +*/ + + +// #define MAX_VERTICES 20 // Constant that defines the maximum number of vertices the graph can have + +// int numVertices = 0; // Stores the current number of vertices +// int matrix[MAX_VERTICES][MAX_VERTICES]; // Distance Matrix +// int components; // To count the number of connected components + +// typedef struct NODE { +// char id; // Vertex identifier +// int numNeighbors; // Number of neighbors +// struct AUX* neighbors[]; // Array of neighboring vertices +// bool visited; // Flag to indicate if the vertex has been visited +// int index; // Stores the order in which the vertex was created +// } *VERTEX; + +// typedef struct AUX { +// VERTEX neighbor; // Pointer to a neighboring vertex +// int value; // Weight of the edge +// } *EDGE; + +// // Function to create a new vertex +// VERTEX createVertex(char id) { +// matrix[numVertices][numVertices] = 0; // Initialize the distance to itself as 0 +// VERTEX newVertex = (VERTEX) malloc(sizeof(NODE)); // Allocate memory for the new vertex +// newVertex->id = id; // Set the vertex identifier +// newVertex->numNeighbors = 0; // Initialize the number of neighbors to 0 +// newVertex->visited = false; // Set the visited flag to false +// newVertex->index = numVertices; // Store the order of creation +// numVertices++; // Increment the number of vertices +// return newVertex; // Return the new vertex +// } + +// // Function to connect two vertices with an edge of given value +// void connectVertex(VERTEX v1, VERTEX v2, int value) { +// matrix[v1->index][v2->index] = value; // Set the distance in the matrix +// EDGE newEdge = (EDGE) malloc(sizeof(AUX)); // Allocate memory for the new edge +// newEdge->neighbor = v2; // Set the neighboring vertex +// newEdge->value = value; // Set the weight of the edge +// v1->neighbors[v1->numNeighbors] = newEdge; // Add the new edge to the list of neighbors +// v1->numNeighbors++; // Increment the number of neighbors +// } + +// // Function to display the distance matrix +// void displayDistanceMatrix() { +// printf("\nDistance Matrix\n"); +// for (int l = 0; l < numVertices; l++) { +// for (int c = 0; c < numVertices; c++) { +// if (matrix[l][c] == -1) +// printf("%d, ", matrix[l][c]); // Print -1 for unreachable vertices +// else +// printf(" %d, ", matrix[l][c]); // Print the distance +// } +// printf("\n"); // New line for the next row +// } +// printf("\n"); +// } + +// // Function to reset the variables +// void resetVariables() { +// for (int l = 0; l < MAX_VERTICES; l++) { +// for (int c = 0; c < MAX_VERTICES; c++) { +// matrix[l][c] = -1; // Set all distances to -1 (unreachable) +// } +// } +// } + +// // Recursive function to visit neighbors +// void visitNeighbors(bool visited[], int current) { +// for (int i = 0; i < numVertices; i++) { +// if (visited[i] == false && matrix[current][i] > 0) { // Check for unvisited neighbors +// visited[i] = true; // Mark as visited +// components++; // Increment the component count +// visitNeighbors(visited, i); // Recursively visit neighbors +// } +// } +// } + +// // Function to calculate connected components +// void calculateConnectedComponents() { +// bool visited[numVertices]; // Array to track visited vertices +// for (int i = 0; i < numVertices; ++i) { +// visited[i] = false; // Initialize all vertices as unvisited +// } +// for (int i = 0; i < numVertices; i++) { +// if (visited[i] == false) { // If the vertex is unvisited +// visited[i] = true; // Mark as visited +// components++; // Increment the component count +// visitNeighbors(visited, i); // Visit its neighbors +// } +// } +// } + +// int main() { +// resetVariables(); // Reset the variables + +// // The distance matrix works according to the order of insertion +// VERTEX A = createVertex('A'); +// VERTEX B = createVertex('B'); +// VERTEX C = createVertex('C'); +// VERTEX D = createVertex('D'); +// VERTEX E = createVertex('E'); + +// // Connect the vertices with edges and weights +// connectVertex(A, B, 5); +// connectVertex(A, C, 6); +// connectVertex(B, D, 8); +// connectVertex(C, D, 4); +// connectVertex(D, B, 2); + +// calculateConnectedComponents(); // Calculate the connected components +// printf("\nConnected Components: %d\n", components); // Print the number of connected components + +// displayDistanceMatrix(); // Show the distance matrix + +// return 0; +// } diff --git a/src/c/HamiltonianCycle.c b/src/c/HamiltonianCycle.c index f54c950c..e6cdbea0 100644 --- a/src/c/HamiltonianCycle.c +++ b/src/c/HamiltonianCycle.c @@ -130,4 +130,155 @@ int main(){ } return 0; -} \ No newline at end of file +} + + + + +// English +/* +* +* Graphs - HAMILTONIAN CYCLE in C +* +* ----------------------------------- +* | | +* (A)---------------(B)-------------(E)---------------(F) +* | | | | +* | | | | +* | | | | +* (C)---------------(D)--------------- | +* | | +* ----------------------------------- +* +* 6 Vertices +* 9 Edges +*/ + +// #define MAX_VERTICES 6 // MAXIMUM NUMBER OF VERTICES IN THE GRAPH; IF THE GRAPH CHANGES, THIS VARIABLE MUST BE UPDATED +// #define MAX_EDGES (MAX_VERTICES * (MAX_VERTICES - 1)) // CALCULATES THE MAXIMUM NUMBER OF EDGES THE GRAPH CAN HAVE + +// // Structure that defines each Vertex of the Graph +// typedef struct NODE { +// char id; +// int numNeighbors; +// struct NODE* neighbors[MAX_EDGES]; +// bool visited; +// }*VERTEX; + +// VERTEX solution[MAX_VERTICES]; // Array to hold the solution of the Hamiltonian cycle + +// // Create a Vertex and return it +// VERTEX createVertex(char id) { +// VERTEX newVertex = (VERTEX)malloc(sizeof(struct NODE)); // Allocate a new Vertex +// if (newVertex == NULL) { +// fprintf(stderr, "Failed to allocate memory for the vertex.\n"); +// exit(EXIT_FAILURE); +// } +// newVertex->id = id; +// newVertex->numNeighbors = 0; +// newVertex->visited = false; +// for (int i = 0; i < MAX_EDGES; i++) { +// newVertex->neighbors[i] = NULL; +// } +// return newVertex; +// } + +// // Connect the vertices passed as parameters +// bool connectVertices(VERTEX v1, VERTEX v2) { +// int aux = 0; +// while (v1->neighbors[aux] != NULL && aux < MAX_EDGES) { // Find the first empty position (NULL) in the neighbors +// aux++; +// } +// if (aux < MAX_EDGES) { +// v1->neighbors[aux] = v2; // Add the new neighbor to the list of neighbors +// aux = 0; +// while (v2->neighbors[aux] != NULL && aux < MAX_EDGES) { // Find the first empty position (NULL) in the neighbors +// aux++; +// } +// if (aux < MAX_EDGES) { +// v2->neighbors[aux] = v1; // Add the new neighbor to the list of neighbors +// v1->numNeighbors++; // Increment the number of neighbors +// v2->numNeighbors++; // Increment the number of neighbors +// return true; +// } +// } +// return false; +// } + +// bool hamiltonianCycleHelper(int aux) { +// if (aux == MAX_VERTICES) { +// for (int i = 0; i < solution[aux - 1]->numNeighbors; i++) { +// if (solution[aux - 1]->neighbors[i] == solution[0]) { +// return true; +// } +// } +// return false; +// } + +// VERTEX s = solution[aux - 1]; // Helper for simplifying the code + +// for (int i = 0; i < s->numNeighbors; i++) { // Traverse all neighbors of the vertex at position aux-1 in the solution array +// if (s->neighbors[i]->visited == false) { +// s->neighbors[i]->visited = true; +// solution[aux] = s->neighbors[i]; +// if (hamiltonianCycleHelper(aux + 1) == true) { +// return true; +// } +// s->neighbors[i]->visited = false; +// } +// } + +// return false; +// } + +// bool hamiltonianCycle(VERTEX graph[MAX_VERTICES]) { +// graph[0]->visited = true; // Mark the starting position as visited +// solution[0] = graph[0]; // Array that will hold the solution of the cycle +// return hamiltonianCycleHelper(1); +// } + +// void freeMemory(VERTEX graph[MAX_VERTICES]) { +// for (int i = 0; i < MAX_VERTICES; i++) { +// free(graph[i]); +// } +// } + +// int main() { +// // Graph set of vertices in an array +// VERTEX GRAPH[MAX_VERTICES]; +// for (char id = 'A'; id < 'A' + MAX_VERTICES; id++) { +// GRAPH[id - 'A'] = createVertex(id); +// } + +// // Connect all vertices according to the GRAPH presented in the introduction +// connectVertices(GRAPH[0], GRAPH[1]); // A - B +// connectVertices(GRAPH[0], GRAPH[2]); // A - C +// connectVertices(GRAPH[1], GRAPH[3]); // B - D +// connectVertices(GRAPH[2], GRAPH[3]); // C - D +// connectVertices(GRAPH[1], GRAPH[4]); // B - E +// connectVertices(GRAPH[3], GRAPH[4]); // D - E +// connectVertices(GRAPH[4], GRAPH[5]); // E - F +// connectVertices(GRAPH[3], GRAPH[5]); // D - F +// connectVertices(GRAPH[1], GRAPH[5]); // B - F + +// for (int i = 0; i < MAX_VERTICES; i++) { +// solution[i] = createVertex('0'); +// } + +// if (hamiltonianCycle(GRAPH)) { +// printf("Hamiltonian Cycle:\n"); +// for (int i = 0; i < MAX_VERTICES; i++) { +// printf("%c", solution[i]->id); +// if (i < MAX_VERTICES - 1) { +// printf(" -> "); +// } +// } +// printf(".\n\n"); +// } else { +// printf("No Hamiltonian Cycle\n"); +// } + +// freeMemory(GRAPH); // Free the allocated memory + +// return 0; +// } diff --git a/src/c/InsertionSort.c b/src/c/InsertionSort.c index 69c9b8fb..22f509e6 100644 --- a/src/c/InsertionSort.c +++ b/src/c/InsertionSort.c @@ -45,4 +45,50 @@ int main() { } printf("\n"); return 0; -} \ No newline at end of file +} + +// In English +/* +Insertion Sort Algorithm in C +*/ + +// // We define the insertion_sort function that takes the array to be sorted and its size n as arguments +// void insertion_sort(int arr[], int n) { +// int i, j, key; +// // Loop through all the elements of the array starting from the second element +// for (i = 1; i < n; i++) { +// // Store the current element value in key +// key = arr[i]; +// // Initialize index j as the previous element to the current element +// j = i - 1; +// // While j is greater than or equal to 0 and the current element is less than the element at index j of the array, +// // move the element at index j one position to the right and decrement j +// while (j >= 0 && arr[j] > key) { +// arr[j + 1] = arr[j]; +// j = j - 1; +// } +// // When the inner loop ends, place the current element in its correct position +// arr[j + 1] = key; +// } +// } + +// // Main function +// int main() { +// int i, n, arr[100]; +// srand(time(NULL)); // Initialize the random seed +// printf("Enter the number of elements in the array: "); +// scanf("%d", &n); +// printf("Input array:\n"); +// for (i = 0; i < n; i++) { +// arr[i] = rand() % 100; // Generate a random value between 0 and 99 +// printf("%d ", arr[i]); // Print the generated value +// } +// printf("\n"); +// insertion_sort(arr, n); +// printf("Sorted array in ascending order:\n"); +// for (i = 0; i < n; i++) { +// printf("%d ", arr[i]); +// } +// printf("\n"); +// return 0; +// } diff --git a/src/c/LinearSearch.c b/src/c/LinearSearch.c index bf28b592..61c08fc4 100644 --- a/src/c/LinearSearch.c +++ b/src/c/LinearSearch.c @@ -19,3 +19,23 @@ int main(){ printf("Valor %d no índice %d\n", 9, buscaSequencial(a, n, 9)); } + +// In english + +// Function for sequential search in an array +// int sequentialSearch(int array[], int size, int target) { +// for (int i = 0; i < size; i++) { +// if (array[i] == target) { +// return i; // Return the index if the target is found +// } +// } +// return -1; // Return -1 if the target is not found +// } + +// int main() { +// int a[] = {1, 2, 3, 4, 5, 6, 7, 8}; // Example array +// int n = sizeof(a) / sizeof(a[0]); // Calculate the number of elements in the array +// printf("Value %d found at index %d\n", 3, sequentialSearch(a, n, 3)); +// printf("Value %d found at index %d\n", 9, sequentialSearch(a, n, 9)); +// return 0; +// } diff --git a/src/c/LinearSearchRecursive.c b/src/c/LinearSearchRecursive.c index ef5159a3..275cab0d 100644 --- a/src/c/LinearSearchRecursive.c +++ b/src/c/LinearSearchRecursive.c @@ -23,3 +23,30 @@ int main(){ 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)); } + +// In english + + +// Recursive function for sequential search in an array +// int recursiveSequentialSearch(int array[], int i, int target, int size) { +// // Base case: if the index reaches the size of the array +// if (i == size) { +// return -1; // Target not found +// } +// // If the current element matches the target +// else if (array[i] == target) { +// return i; // Return the index +// } +// // Recursively call the function for the next index +// else { +// return recursiveSequentialSearch(array, i + 1, target, size); +// } +// } + +// int main() { +// int array[] = {1, 2, 3, 4, 5, 6, 7, 8}; // Example array +// size_t n = sizeof(array) / sizeof(array[0]); // Calculate the number of elements in the array +// printf("Value %d found at index %d\n", 1, recursiveSequentialSearch(array, 0, 1, n)); +// printf("Value %d found at index %d\n", 10, recursiveSequentialSearch(array, 0, 10, n)); +// return 0; +// } diff --git a/src/c/LinearSearchSentinel.c b/src/c/LinearSearchSentinel.c index 67f32822..9e6f2527 100644 --- a/src/c/LinearSearchSentinel.c +++ b/src/c/LinearSearchSentinel.c @@ -41,3 +41,49 @@ int main(){ return 0; } + + +// In english + +/* +* Sentinel Search Example in C +* Objective: Find a value in an array without needing to test all values within the loop +*/ + + +// #define ARRAY_SIZE 10 + +// // Sentinel search function that performs a sequential search without testing the key at each iteration +// int sentinelSearch(int array[], int key) { +// array[ARRAY_SIZE] = key; // Place the searched value (key) at the last position of the array +// int index = 0; // Control variable for the loop +// // While the current element is not the key, increment index +// while (array[index] != key) +// index++; + +// // If index equals the size of the array, it means the search went to the end without finding the key +// if (index == ARRAY_SIZE) +// return -1; // Not found +// else // If index is different, it means the value was found +// return index; // Found +// } + +// int main() { +// int array[ARRAY_SIZE + 1]; // Declare the array with +1 because this position will be used by the sentinel + +// // Fill the array with random values between 0 and 1000 +// srand(time(NULL)); +// for (int i = 0; i < ARRAY_SIZE; i++) { +// array[i] = rand() % 1000; +// printf("%d, ", array[i]); +// } + +// // Perform the search, passing the array and the key to search for +// int res = sentinelSearch(array, array[ARRAY_SIZE - 2]); +// if (res != -1) +// printf("\n\nValue %d found at position %d.\n\n", array[res], res); +// else +// printf("\n\nValue not found in the array\n\n"); + +// return 0; +// } diff --git a/src/c/MaxRecursive.c b/src/c/MaxRecursive.c index 9c9ac09e..2ac7b247 100644 --- a/src/c/MaxRecursive.c +++ b/src/c/MaxRecursive.c @@ -87,3 +87,75 @@ int main() return 0; } + + + +// In english + +/* +* Examples of functions to find the maximum number in an array +* All 3 are recursive, but only MaxDC uses divide and conquer +*/ + +// #define MAX 10 + +// // Maximum using Divide and Conquer +// int MaxDC(int *array, int start, int end) { +// int leftMax, rightMax; +// int mid = (start + end) / 2; + +// if (start == end) { +// return array[start]; +// } + +// leftMax = MaxDC(array, start, mid); +// rightMax = MaxDC(array, mid + 1, end); + +// if (leftMax > rightMax) { +// return leftMax; +// } else { +// return rightMax; +// } +// } + +// void max1(int *array, int maximum, int index) { +// if (array[index] > maximum) { +// maximum = array[index]; +// } + +// if (index < MAX - 1) { +// max1(array, maximum, index + 1); +// } else { +// printf("\n\nMax1: %d\n", maximum); +// } +// } + +// int max2(int array[], int size) { +// if (size == 1) { +// return array[0]; // only 1 element +// } else { +// int x = max2(array, size - 1); + +// if (x > array[size - 1]) { +// return x; +// } else { +// return array[size - 1]; +// } +// } +// } + +// int main() { +// int array[MAX]; + +// for (int i = 0; i < MAX; ++i) { +// array[i] = (rand() % 90) + 10; // Generates numbers from 10 to 99 +// printf("%d, ", array[i]); +// } + +// max1(array, array[0], 1); + +// printf("\nMax2: %d\n", max2(array, MAX)); +// printf("\nMaxDC: %d\n\n", MaxDC(array, 0, MAX - 1)); + +// return 0; +// } diff --git a/src/c/MergeSort.c b/src/c/MergeSort.c index f536e462..0f9056f1 100644 --- a/src/c/MergeSort.c +++ b/src/c/MergeSort.c @@ -70,4 +70,75 @@ int main(){ } return 0; -} \ No newline at end of file +} + +// In english + +/* +* Example of Sorting using Merge Sort +* +* Divide and Conquer: +* +* Divide: Split the data into small subsequences; +* Conquer: Sort the two halves recursively using merge sort; +* Combine: Merge the two halves into a single sorted set. +* +*/ + + +// #define ARRAY_SIZE 100 + +// void merge(int array[], int size) { +// int mid = size / 2; +// int i = 0, j = mid, k = 0; +// int temp[size]; + +// while (i < mid && j < size) { +// if (array[i] <= array[j]) +// temp[k] = array[i++]; +// else +// temp[k] = array[j++]; +// k++; +// } + +// if (i == mid) +// while (j < size) +// temp[k++] = array[j++]; +// else +// while (i < mid) +// temp[k++] = array[i++]; + +// for (i = 0; i < size; i++) +// array[i] = temp[i]; +// } + +// void mergeSort(int array[], int size) { +// int mid = size / 2; + +// if (size > 1) { +// mergeSort(array, mid); +// mergeSort(array + mid, size - mid); +// merge(array, size); +// } +// } + +// int main() { +// int array[ARRAY_SIZE]; + +// // Fill the array with random values 0-1000 +// srand(time(NULL)); +// for (int i = 0; i < ARRAY_SIZE; i++) { +// array[i] = rand() % 1000; +// printf("%d, ", array[i]); +// } + +// printf("\n\n"); + +// mergeSort(array, ARRAY_SIZE); + +// for (int i = 0; i < ARRAY_SIZE; i++) { +// printf("%d, ", array[i]); +// } + +// return 0; +// } diff --git a/src/c/MinMaxRecursive.c b/src/c/MinMaxRecursive.c index fcb64997..c175d922 100644 --- a/src/c/MinMaxRecursive.c +++ b/src/c/MinMaxRecursive.c @@ -1,6 +1,8 @@ /* * Exemplo de algoritmo recursivo. * Objetivo: encontrar o valor máximo e mínimo em um vetor, utilizando recursividade +* Example of a recursive algorithm. +* Objective: Find the maximum and minimum values in an array using recursion. */ #include diff --git a/src/c/Palindrome.c b/src/c/Palindrome.c index 6698f6dd..39b024d7 100644 --- a/src/c/Palindrome.c +++ b/src/c/Palindrome.c @@ -35,3 +35,44 @@ int main() { return 0; } + + +// In english + +// #define MAX_SIZE_WORD 100 + +// // Function to reverse the input string +// void calc_reverse(char *input, char *output) { +// size_t len_input = strlen(input); // Get the length of the input string + +// char *last_char = input + len_input - 1; // Point to the last character of the input + +// // Reverse the input string +// for (int i = 0; i < len_input; i++) { +// output[i] = *(last_char - i); // Copy characters in reverse order +// } +// output[len_input] = '\0'; // Null-terminate the output string +// } + +// int main() { +// char input[MAX_SIZE_WORD]; // Array to hold the input word +// char reverse[MAX_SIZE_WORD]; // Array to hold the reversed word + +// printf("Enter a word: "); // Prompt the user for input + +// fgets(input, MAX_SIZE_WORD, stdin); // Read a line of input +// // Remove newline character from the end +// input[strlen(input) - 1] = '\0'; + +// calc_reverse(input, reverse); // Call the function to reverse the word + +// printf("Your reversed word: %s\n", reverse); // Print the reversed word + +// // Check if the input word is a palindrome +// if (!strcmp(input, reverse)) +// puts("Your word is a palindrome!"); // If it is a palindrome +// else +// puts("Your word is NOT a palindrome!"); // If it is not + +// return 0; +// } diff --git a/src/c/Queue.c b/src/c/Queue.c index 75efce52..86e6573f 100644 --- a/src/c/Queue.c +++ b/src/c/Queue.c @@ -77,4 +77,95 @@ int main(){ printf("A chave buscada se encontra na posicao %d da fila\n\n", buscaFila(8, &fi) ); return 0; -} \ No newline at end of file +} + + +// In english +/* +* Example implementation of a Queue in C +*/ + + +// #define MAX 10 +// #define ERROR -1 + +// typedef int KEY_TYPE; + +// typedef struct { +// KEY_TYPE key; // The key of the record +// } RECORD; + +// typedef struct { +// RECORD A[MAX + 1]; // Array to store the queue records +// int numRecords; // Number of records in the queue +// } QUEUE; + +// // Function to initialize the queue +// void initialize(QUEUE* Q) { +// int i = 0; +// // Initialize the queue with even numbers +// for (i; i < MAX - 2; i++) { +// Q->A[i].key = i * 2; // Store even numbers +// } +// Q->numRecords = i; // Set the number of records +// } + +// // Function to display the queue +// void showQueue(QUEUE* Q) { +// int i = 0; +// printf("QUEUE:\n"); +// // Print all elements in the queue +// for (i; i < Q->numRecords; i++) { +// printf("[ %d ] ", Q->A[i].key); +// } +// printf("\n\n"); +// } + +// // Function to insert a key into the queue +// bool insertQueue(KEY_TYPE key, QUEUE* Q) { +// if (Q->numRecords >= MAX) // Check if the queue is full +// return false; +// Q->A[Q->numRecords].key = key; // Insert the key at the end +// Q->numRecords++; // Increment the number of records +// return true; +// } + +// // Function to remove an element from the queue +// bool removeQueue(QUEUE* Q) { +// if (Q->numRecords <= 0) // Check if the queue is empty +// return false; +// int i = 1; +// // Shift all elements to the front +// for (i; i < Q->numRecords; i++) { +// Q->A[i - 1].key = Q->A[i].key; // Move the elements +// } +// Q->numRecords--; // Decrement the number of records +// return true; +// } + +// // Function to search for a key in the queue +// int searchQueue(KEY_TYPE key, QUEUE* Q) { +// Q->A[Q->numRecords].key = key; // Place the key at the end for sentinel search +// int i = 0; +// // Search for the key +// while (Q->A[i].key != key) +// i++; +// if (i >= Q->numRecords) // If the key was not found +// return ERROR; +// return i; // Return the index where the key was found +// } + +// int main() { +// QUEUE q; // Declare the queue +// initialize(&q); // Initialize the queue +// showQueue(&q); // Display the queue + +// insertQueue(15, &q); // Insert a new key +// showQueue(&q); // Display the updated queue + +// removeQueue(&q); // Remove the front element +// showQueue(&q); // Display the queue after removal + +// printf("The searched key is located at position %d in the queue\n\n", searchQueue(8, &q)); +// return 0; +// } diff --git a/src/c/QuickSort.c b/src/c/QuickSort.c index 98c49507..fadb5336 100644 --- a/src/c/QuickSort.c +++ b/src/c/QuickSort.c @@ -84,4 +84,105 @@ int main() { quicksort_hoare(example_hoare, 0, size - 1); print_array(example_hoare, size); return 0; -} \ No newline at end of file +} + + +// In english + +// Function to print the contents of an array +// 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(" ]\n"); +// } + +// // Function to swap two elements in the array +// 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; +// } + +// // Lomuto partition scheme +// int lomuto_partition(int array[], int low, int high) { +// int pivot = array[high]; // Choosing the last element as the pivot +// int index = low; // Index of the smaller element + +// // Rearranging the array based on the pivot +// for (int j = low; j < high; ++j) { +// if (array[j] < pivot) { // If the current element is less than the pivot +// swap(array, index, j); // Swap it with the index +// ++index; // Move the index forward +// } +// } +// swap(array, index, high); // Place the pivot in the correct position +// return index; // Return the index of the pivot +// } + +// // Quick Sort using the Lomuto partition scheme +// void quicksort_lomuto(int array[], int low, int high) { +// if (low < high) { // Base case for recursion +// int pivot = lomuto_partition(array, low, high); // Partitioning the array +// quicksort_lomuto(array, low, pivot - 1); // Recursively sort the left half +// quicksort_lomuto(array, pivot + 1, high); // Recursively sort the right half +// } +// } + +// // Hoare partition scheme +// int hoare_partition(int array[], int low, int high) { +// int pivot = array[low]; // Choosing the first element as the pivot +// int i = low - 1; // Left index +// int j = high + 1; // Right index + +// while (true) { +// // Increment i until an element greater than or equal to the pivot is found +// do { +// ++i; +// } while (array[i] < pivot); + +// // Decrement j until an element less than or equal to the pivot is found +// do { +// --j; +// } while (array[j] > pivot); + +// // If the indices cross, return the j index +// if (i >= j) { +// return j; +// } +// swap(array, i, j); // Swap elements at i and j +// } +// } + +// // Quick Sort using the Hoare partition scheme +// void quicksort_hoare(int array[], int low, int high) { +// if (low < high) { // Base case for recursion +// int pivot = hoare_partition(array, low, high); // Partitioning the array +// quicksort_hoare(array, low, pivot); // Recursively sort the left half +// quicksort_hoare(array, pivot + 1, high); // Recursively sort the right half +// } +// } + +// int main() { +// int example_lomuto[] = {5, 3, 1, 4, 2}; // Example array for Lomuto +// int example_hoare[] = {5, 3, 1, 4, 2}; // Example array for Hoare +// int size = 5; // Size of the arrays + +// // Using the Lomuto partition scheme +// printf("Lomuto quicksort partition:\n"); +// print_array(example_lomuto, size); // Print the original array +// quicksort_lomuto(example_lomuto, 0, size - 1); // Perform Quick Sort +// print_array(example_lomuto, size); // Print the sorted array + +// // Using the Hoare partition scheme +// printf("Hoare quicksort partition:\n"); +// print_array(example_hoare, size); // Print the original array +// quicksort_hoare(example_hoare, 0, size - 1); // Perform Quick Sort +// print_array(example_hoare, size); // Print the sorted array + +// return 0; // End of the program +// } diff --git a/src/c/SinglyLinkedList.c b/src/c/SinglyLinkedList.c index 9e5cad76..4cd72ab8 100644 --- a/src/c/SinglyLinkedList.c +++ b/src/c/SinglyLinkedList.c @@ -270,3 +270,288 @@ int main() { return 0; } + +// In english + + +// Define a node structure +// typedef struct Node { +// int data; // Data contained in the node +// struct Node* previous; // Pointer to the previous node +// struct Node* next; // Pointer to the next node +// } NodeType; + +// typedef NodeType* NodePointer; + +// // Define a list header structure +// typedef struct { +// int size; // Size of the list +// NodePointer first; // Pointer to the first node +// NodePointer last; // Pointer to the last node +// } ListHeader; + +// typedef ListHeader* List; + +// // Function to create a new list +// List createList() { +// List list = (ListHeader*)malloc(sizeof(ListHeader)); + +// list->size = 0; // Initialize size to 0 +// list->first = NULL; // Initialize first pointer to NULL +// list->last = NULL; // Initialize last pointer to NULL + +// return list; +// } + +// // Function to append a new element to the list +// List appendList(List lst, int data) { +// NodePointer newNode = (NodeType*)malloc(sizeof(NodeType)); + +// newNode->data = data; // Set the data of the new node +// newNode->previous = lst->last; // Set previous pointer to the current last node +// newNode->next = NULL; // Set next pointer to NULL + +// if (lst->size == 0) { +// lst->first = newNode; // If the list is empty, set first pointer +// } else { +// lst->last->next = newNode; // Link the new node to the end of the list +// } + +// lst->last = newNode; // Update last pointer to the new node +// lst->size++; // Increment the size of the list + +// return lst; +// } + +// // Function to get the size of the list +// int lengthList(List lst) { +// return lst->size; +// } + +// // Function to get the first element of the list +// int firstList(List lst) { +// return lst->first->data; +// } + +// // Function to get the last element of the list +// int lastList(List lst) { +// return lst->last->data; +// } + +// // Function to insert a new element at a specific index +// List insertList(List lst, int index, int data) { +// int size = lengthList(lst); + +// if ((index < 0) || (index > size)) { +// return NULL; // Return NULL if index is invalid +// } + +// if ((lengthList(lst) == 0) || (index == size)) { +// appendList(lst, data); // Append to the end if index is size +// } else { +// NodePointer newNode = (NodeType*)malloc(sizeof(NodeType)); +// newNode->data = data; + +// if (index == 0) { +// newNode->next = lst->first; // Insert at the beginning +// lst->first = newNode; +// } else { +// NodePointer aux = lst->first; +// int pos = 0; + +// while (pos != (index - 1)) { +// aux = aux->next; // Traverse to the node before the insert position +// pos++; +// } +// newNode->next = aux->next; // Link new node to the next node +// aux->next = newNode; // Link the previous node to the new node +// } + +// lst->size++; // Increment the size of the list +// } + +// return lst; +// } + +// // Function to retrieve a node at a specific index +// NodePointer infoList(List lst, int index) { +// int size = lengthList(lst); + +// if ((size == 0) || (index < 0) || (index > size)) { +// return NULL; // Return NULL if index is invalid +// } + +// if (index == 0) { +// return lst->first; // Return first node if index is 0 +// } + +// if (index == size - 1) { +// return lst->last; // Return last node if index is last +// } + +// NodePointer aux = lst->first; +// int pos = 0; + +// while (pos != index) { +// aux = aux->next; // Traverse to the specified index +// pos++; +// } + +// return aux; // Return the node at the specified index +// } + +// // Function to remove a node at a specific index +// void removeList(List lst, int index) { +// int size = lengthList(lst); + +// if ((index < 0) || (index > size) || (size == 0)) { +// printf("Error: index does not exist in the list."); +// return; // Print error if index is invalid +// } + +// if (size == 1) { +// NodePointer aux = lst->first; +// lst->first = NULL; // Empty the list +// lst->last = NULL; +// lst->size--; + +// free(aux); // Free the memory of the removed node +// } else { +// if (index == 0) { +// NodePointer aux = lst->first; +// lst->first = aux->next; // Update first node +// lst->size--; + +// free(aux); // Free the memory of the removed node +// } else { +// if (index == size - 1) { +// NodePointer aux = lst->last; + +// NodePointer penultimate = lst->first; +// int pos = 0; + +// while (pos != index - 1) { +// penultimate = penultimate->next; // Find the penultimate node +// pos++; +// } + +// penultimate->next = NULL; // Update the penultimate node's next pointer +// lst->last = penultimate; // Update last pointer + +// lst->size--; + +// free(aux); // Free the memory of the removed node +// } else { +// NodePointer previous = lst->first; +// int pos = 0; + +// while (pos != index - 1) { +// previous = previous->next; // Find the node before the one to be removed +// pos++; +// } + +// NodePointer aux = previous->next; +// previous->next = aux->next; // Bypass the removed node +// lst->size--; + +// free(aux); // Free the memory of the removed node +// } +// } +// } +// } + +// // Function to find the index of a specific value +// int indexList(List lst, int data) { +// int size = lengthList(lst); +// int i, listData; +// NodePointer nodeData; + +// if (size == 0) { +// return -1; // Return -1 if the list is empty +// } + +// i = 0; +// nodeData = infoList(lst, i); +// listData = nodeData->data; +// while ((i < size) && (data != listData)) { +// i++; +// nodeData = infoList(lst, i); // Get next node data +// listData = nodeData->data; +// } + +// if (i < size) { +// return i; // Return the index if found +// } + +// return -1; // Return -1 if not found +// } + +// // Function to clear the list +// List clearList(List lst) { +// int size = lengthList(lst); + +// if (size == 0) { +// return lst; // Return if the list is already empty +// } + +// while (lengthList(lst) > 0) { +// removeList(lst, 0); // Remove all elements +// } + +// return lst; +// } + +// // Function to clone the list +// List cloneList(List lst) { +// List clone = createList(); +// int size = lengthList(lst); + +// if (size == 0) { +// return clone; // Return an empty clone if the list is empty +// } + +// for (int i = 0; i < size; i++) { +// NodePointer node = infoList(lst, i); +// if (node != NULL) { +// appendList(clone, node->data); // Append data to the clone list +// } +// } + +// return clone; // Return the cloned list +// } + +// // Main function to demonstrate the list operations +// int main() { +// List list = createList(); +// appendList(list, 3); +// appendList(list, 5); +// appendList(list, 7); + +// printf("List created and added 3 numbers\n"); +// int size = lengthList(list); +// int first = firstList(list); +// int last = lastList(list); +// NodePointer value = infoList(list, 1); +// int valueData = value->data; +// printf("Size of the list: %d\nFirst element of the list: %d\nLast element of the list: %d\nSecond value: %d\n", size, first, last, valueData); + +// insertList(list, 2, 6); +// value = infoList(list, 2); +// valueData = value->data; +// printf("Adding 6 at position 2: %d\n", valueData); + +// removeList(list, 1); +// size = lengthList(list); +// printf("New size after adding and removing: %d\n", size); + +// int index = indexList(list, 3); +// printf("Index of the element with value 3 in the list: %d\n", index); + +// List clonedList = cloneList(list); +// printf("List duplicated\n"); + +// clearList(list); +// printf("List cleared\n"); + +// return 0; +// } diff --git a/src/c/SortedLinkedList.c b/src/c/SortedLinkedList.c index 29c37489..65b65350 100644 --- a/src/c/SortedLinkedList.c +++ b/src/c/SortedLinkedList.c @@ -101,4 +101,111 @@ int main(){ mostraLista(&LISTA); return 0; -} \ No newline at end of file +} + + +// In english + +/* +* Example implementation of a Sorted Sequential List in C - Using Sentinel +*/ + + +// #define MAX 10 +// #define ERROR -1 + +// typedef int KEYTYPE; // Define a name KEYTYPE for an integer type + +// typedef struct { +// KEYTYPE key; +// } RECORD; + +// typedef struct { +// RECORD A[MAX + 1]; // The +1 is the position that will be used for the 'sentinel' +// int numElements; +// } LIST; + +// void initialize(LIST* L) { +// L->numElements = 0; // Access the list by its memory address +// int i = 0; +// for (i; i < MAX - 2; ++i) { // Fill the list up to -2 to leave space for future insertions +// L->A[i].key = i * 2; +// } +// L->numElements = MAX - 2; +// // (*L).numElements = 0; // In this case, it would access the list itself, not the pointer +// } + +// /* The purpose of the sentinel function is to add the key at the end of the list, +// * so it will always find the key, even if it's in the last position of the list. +// * If it's the last element, it means it wasn't found. +// * Thus, this eliminates the 'if' inside the loop, saving several comparisons +// */ +// int sentinelSearch(KEYTYPE ch, LIST* L) { // Could use binary search here, which would be more appropriate. +// int i = 0; +// L->A[L->numElements].key = ch; // Assigns the 'key'/searched value to the last position of array A +// while (L->A[i].key != ch) // Traverses the entire array A to check if the 'key'/searched value is in the array (otherwise it will be the sentinel) +// i++; +// if (i == L->numElements) // If the value reached the end, it means it wasn't found, return ERROR (-1) +// return ERROR; +// return i; // Otherwise, return the position of the value/'key' in the array +// } + +// bool insertOrdered(RECORD reg, LIST* L) { +// int i = 0; +// if (L->numElements >= MAX) +// return false; +// L->A[L->numElements].key = reg.key; +// while (L->A[i].key < reg.key) +// i++; +// int p = L->numElements - 1; +// while (p >= i) { +// L->A[p + 1] = L->A[p]; +// p--; +// } +// L->A[i] = reg; +// L->numElements++; +// return true; +// } + +// bool deleteValue(RECORD reg, LIST* L) { +// int position = sentinelSearch(reg.key, L); +// if (position >= 0) { +// for (position; position < L->numElements; position++) { +// L->A[position] = L->A[position + 1]; +// } +// L->numElements--; +// return true; +// } else { +// return false; +// } +// } + +// void showList(LIST* L) { +// int i = 0; +// for (i; i < L->numElements; ++i) { // Traverses and shows all values in the array +// printf("%d, ", L->A[i].key); +// } +// printf("\n\n"); +// } + +// int main() { + +// LIST LISTA; +// initialize(&LISTA); + +// printf("Value 10 found at position: %d\n\n", sentinelSearch(10, &LISTA)); +// showList(&LISTA); + +// RECORD reg; +// reg.key = 7; +// printf("Inserting value: %d\n", reg.key); +// insertOrdered(reg, &LISTA); +// showList(&LISTA); + +// reg.key = 12; +// printf("Deleting value: %d\n", reg.key); +// deleteValue(reg, &LISTA); +// showList(&LISTA); + +// return 0; +// } diff --git a/src/c/Stack.c b/src/c/Stack.c index 4f91e9f4..e67699ce 100644 --- a/src/c/Stack.c +++ b/src/c/Stack.c @@ -81,4 +81,91 @@ int main(){ }else{ printf("Valor nao encontrado\n"); } -} \ No newline at end of file +} + + +// In english + +/* +* Example implementation of a Stack in C - Uses Sentinel +*/ + + +// #define MAX 10 +// #define ERROR -1 + +// typedef int KEYTYPE; + +// typedef struct { +// KEYTYPE key; +// } RECORD; + +// typedef struct { +// RECORD A[MAX + 1]; +// int numRecords; +// } STACK; + +// int initialize(STACK* p) { +// p->numRecords = 0; +// int i = 0; +// for (i; i < MAX - 2; i++) { // Fill the Stack for testing +// p->A[i].key = i * 2; // It's an array of RECORD (similar to a class); it could have more fields, hence A[i].key, it will insert the value in the key field +// } +// p->numRecords = i; +// } + +// bool insertStack(int value, STACK* p) { +// if (p->numRecords < MAX) { +// p->A[p->numRecords].key = value; +// p->numRecords++; +// return true; +// } else { +// return false; +// } +// } + +// bool removeStack(STACK* p) { +// p->numRecords--; +// } + +// void showStack(STACK* p) { +// int i = p->numRecords - 1; +// printf("\nStack:\n"); +// for (i; i >= 0; i--) { +// printf("%d = [ %d ]\n", i, p->A[i].key); +// } +// printf("------------------\n"); +// } + +// int searchStack(int key, STACK* p) { +// p->A[p->numRecords].key = key; +// int aux = 0; +// while (p->A[aux].key != key) +// aux++; +// if (aux == p->numRecords) +// return ERROR; +// return aux; +// } + +// int main() { +// STACK vStack; +// initialize(&vStack); + +// showStack(&vStack); +// if (insertStack(10, &vStack)) { +// printf("Inserted successfully"); +// } else { +// printf("Stack is full"); +// } + +// showStack(&vStack); +// removeStack(&vStack); +// showStack(&vStack); + +// int aux = searchStack(8, &vStack); +// if (aux != -1) { +// printf("Value 8 found at position %d in the stack\n", aux); +// } else { +// printf("Value not found\n"); +// } +// } diff --git a/src/c/TravellingSalesman.c b/src/c/TravellingSalesman.c index b7924423..4a6c2802 100644 --- a/src/c/TravellingSalesman.c +++ b/src/c/TravellingSalesman.c @@ -104,4 +104,112 @@ int main(){ printf("%d, ", melhorSolucao[i]); } printf("\n\n"); -} \ No newline at end of file +} + + +// In english + + +/* +* 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 +*/ + + +// #define VERTICES 5 +// #define INFINITY 429496729 // A large value representing infinity + +// int tempSolution[VERTICES]; +// int bestSolution[VERTICES]; +// bool visited[VERTICES]; +// int bestSolutionValue = INFINITY; +// int currentSolutionValue = 0; + +// // Distance matrix representing the graph +// 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 travelingSalesmanAux(int x) { +// // If the current solution value is already greater than the best solution value, stop since it can't be the best solution +// if (currentSolutionValue > bestSolutionValue) +// return; + +// if (x == VERTICES) { // If x == VERTICES means the temporary solution array is complete +// int distance = matrix[tempSolution[x - 1]][tempSolution[0]]; +// // If a better solution is found +// if (distance < INFINITY && currentSolutionValue + distance < bestSolutionValue) { +// bestSolutionValue = currentSolutionValue + distance; // Update best solution value +// // 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 vertex in the temporary solution array +// // Loop through all columns of the matrix at the row of the last vertex in the temporary solution array +// for (int i = 0; i < VERTICES; i++) { +// // If position i in the array has not been visited, and if the matrix value at the position 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 total path cost +// travelingSalesmanAux(x + 1); // Recursively call for the next vertex +// currentSolutionValue -= matrix[last][i]; // If not done yet, decrement the current solution value +// visited[i] = false; // Mark as unvisited for use by another vertex +// } +// } +// } + +// void travelingSalesman(int start) { +// visited[start] = true; // Mark the first vertex as visited (0) +// tempSolution[0] = start; // Put vertex 0 in the first position of the temporary solution array +// travelingSalesmanAux(1); // Call the auxiliary method for the traveling salesman problem +// } + +// void initializeVectors() { +// for (int i = 0; i < VERTICES; i++) { +// visited[i] = false; +// tempSolution[i] = -1; +// bestSolution[i] = -1; +// } +// } + +// int main() { +// initializeVectors(); +// travelingSalesman(0); + +// 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/UnorderedLinkedList.c b/src/c/UnorderedLinkedList.c index 16490bfe..739263b7 100644 --- a/src/c/UnorderedLinkedList.c +++ b/src/c/UnorderedLinkedList.c @@ -82,4 +82,95 @@ int main(){ deletaRegistro(34, RG); mostraLista(RG); return 0; -} \ No newline at end of file +} + +// In enlgish + +/* +* Example of a Dynamic Unordered Linked List in C +*/ + +// #include +// #include // Changed from to + +// #define ERROR -1 + +// typedef int KEY_TYPE; + +// typedef struct aux { +// KEY_TYPE key; +// struct aux *next; +// } RECORD, *POINTER; + +// POINTER createRecord(KEY_TYPE ch) { +// POINTER rg = (POINTER) malloc(sizeof(RECORD)); // Allocating memory for a new record +// rg->key = ch; // Assigning the key value +// rg->next = NULL; // Initializing the next pointer to NULL +// return rg; +// } + +// POINTER insertRecord(KEY_TYPE ch, POINTER rg) { +// if (rg == NULL) +// return createRecord(ch); // If the list is empty, create a new record +// while (rg->next != NULL) +// rg = rg->next; // Move to the end of the list +// rg->next = createRecord(ch); // Insert the new record at the end +// return NULL; +// } + +// void displayList(POINTER rg) { +// if (rg == NULL) return; // Base case for recursion +// printf("%d, ", rg->key); // Print the current key +// displayList(rg->next); // Recursively display the next records +// } + +// POINTER sequentialSearch(KEY_TYPE ch, POINTER rg) { +// while (rg != NULL) { +// if (rg->key == ch) +// return rg; // Return the record if the key matches +// rg = rg->next; // Move to the next record +// } +// return NULL; // Key not found +// } + +// bool deleteRecord(KEY_TYPE ch, POINTER rg) { +// POINTER prev = NULL; // Pointer to the previous record +// while (rg != NULL) { +// if (rg->key == ch) { +// if (prev != NULL) { +// prev->next = rg->next; // Bypass the current record +// } +// free(rg); // Free memory of the deleted record +// return true; // Return success +// } +// prev = rg; // Move prev to current +// rg = rg->next; // Move to the next record +// } +// printf("\nKey %d not found.\n", ch); +// return false; +// } + +// int main() { +// POINTER RG = NULL; // Initialize the head of the list as NULL +// RG = insertRecord(23, RG); // Insert records into the list +// insertRecord(34, RG); +// insertRecord(12, RG); +// insertRecord(63, RG); +// insertRecord(45, RG); + +// displayList(RG); // Display the list + +// KEY_TYPE ch = 64; +// if (sequentialSearch(ch, RG) != NULL) +// printf("\nFound key %d\n", ch); +// else +// printf("\nKey %d not found\n", ch); + +// deleteRecord(63, RG); // Delete a record +// displayList(RG); // Display the list again + +// printf("\n"); +// deleteRecord(34, RG); // Delete another record +// displayList(RG); // Display the list again +// return 0; +// }