diff --git a/client_server/UDP_Client.c b/client_server/UDP_Client.c index e352c53b..194847a6 100644 --- a/client_server/UDP_Client.c +++ b/client_server/UDP_Client.c @@ -1,49 +1,49 @@ -// Client side implementation of UDP client-server model -#include -#include -#include -#include -#include -#include -#include -#include +// Client side implementation of UDP client-server model +#include +#include +#include +#include +#include +#include +#include +#include -#define PORT 8080 -#define MAXLINE 1024 +#define PORT 8080 +#define MAXLINE 1024 -// Driver code -int main() { - int sockfd; - char buffer[MAXLINE]; - char *hello = "Hello from client"; - struct sockaddr_in servaddr; +// Driver code +int main() +{ + int sockfd; + char buffer[MAXLINE]; + char *hello = "Hello from client"; + struct sockaddr_in servaddr; - // Creating socket file descriptor - if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) { - perror("socket creation failed"); - exit(EXIT_FAILURE); - } + // Creating socket file descriptor + if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) + { + perror("socket creation failed"); + exit(EXIT_FAILURE); + } - memset(&servaddr, 0, sizeof(servaddr)); - - // Filling server information - servaddr.sin_family = AF_INET; - servaddr.sin_port = htons(PORT); - servaddr.sin_addr.s_addr = INADDR_ANY; - - int n, len; - - sendto(sockfd, (const char *)hello, strlen(hello), - MSG_CONFIRM, (const struct sockaddr *) &servaddr, - sizeof(servaddr)); - printf("Hello message sent.\n"); - - n = recvfrom(sockfd, (char *)buffer, MAXLINE, - MSG_WAITALL, (struct sockaddr *) &servaddr, - &len); - buffer[n] = '\0'; - printf("Server : %s\n", buffer); + memset(&servaddr, 0, sizeof(servaddr)); - close(sockfd); - return 0; -} + // Filling server information + servaddr.sin_family = AF_INET; + servaddr.sin_port = htons(PORT); + servaddr.sin_addr.s_addr = INADDR_ANY; + + int n, len; + + sendto(sockfd, (const char *)hello, strlen(hello), MSG_CONFIRM, + (const struct sockaddr *)&servaddr, sizeof(servaddr)); + printf("Hello message sent.\n"); + + n = recvfrom(sockfd, (char *)buffer, MAXLINE, MSG_WAITALL, + (struct sockaddr *)&servaddr, &len); + buffer[n] = '\0'; + printf("Server : %s\n", buffer); + + close(sockfd); + return 0; +} diff --git a/client_server/UDP_Server.c b/client_server/UDP_Server.c index 0fb36c16..5342bf6d 100644 --- a/client_server/UDP_Server.c +++ b/client_server/UDP_Server.c @@ -1,55 +1,54 @@ -// Server side implementation of UDP client-server model -#include -#include -#include -#include -#include -#include -#include -#include +// Server side implementation of UDP client-server model +#include +#include +#include +#include +#include +#include +#include +#include -#define PORT 8080 -#define MAXLINE 1024 +#define PORT 8080 +#define MAXLINE 1024 -// Driver code -int main() { - int sockfd; - char buffer[MAXLINE]; - char *hello = "Hello from server"; - struct sockaddr_in servaddr, cliaddr; - - // Creating socket file descriptor - if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) { - perror("socket creation failed"); - exit(EXIT_FAILURE); - } - - memset(&servaddr, 0, sizeof(servaddr)); - memset(&cliaddr, 0, sizeof(cliaddr)); - - // Filling server information - servaddr.sin_family = AF_INET; // IPv4 - servaddr.sin_addr.s_addr = INADDR_ANY; - servaddr.sin_port = htons(PORT); - - // Bind the socket with the server address - if ( bind(sockfd, (const struct sockaddr *)&servaddr, - sizeof(servaddr)) < 0 ) - { - perror("bind failed"); - exit(EXIT_FAILURE); - } - - int len, n; - n = recvfrom(sockfd, (char *)buffer, MAXLINE, - MSG_WAITALL, ( struct sockaddr *) &cliaddr, - &len); - buffer[n] = '\0'; - printf("Client : %s\n", buffer); - sendto(sockfd, (const char *)hello, strlen(hello), - MSG_CONFIRM, (const struct sockaddr *) &cliaddr, - len); - printf("Hello message sent.\n"); - - return 0; -} +// Driver code +int main() +{ + int sockfd; + char buffer[MAXLINE]; + char *hello = "Hello from server"; + struct sockaddr_in servaddr, cliaddr; + + // Creating socket file descriptor + if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) + { + perror("socket creation failed"); + exit(EXIT_FAILURE); + } + + memset(&servaddr, 0, sizeof(servaddr)); + memset(&cliaddr, 0, sizeof(cliaddr)); + + // Filling server information + servaddr.sin_family = AF_INET; // IPv4 + servaddr.sin_addr.s_addr = INADDR_ANY; + servaddr.sin_port = htons(PORT); + + // Bind the socket with the server address + if (bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) + { + perror("bind failed"); + exit(EXIT_FAILURE); + } + + int len, n; + n = recvfrom(sockfd, (char *)buffer, MAXLINE, MSG_WAITALL, + (struct sockaddr *)&cliaddr, &len); + buffer[n] = '\0'; + printf("Client : %s\n", buffer); + sendto(sockfd, (const char *)hello, strlen(hello), MSG_CONFIRM, + (const struct sockaddr *)&cliaddr, len); + printf("Hello message sent.\n"); + + return 0; +} diff --git a/client_server/client.c b/client_server/client.c index ee326754..2c45ae41 100644 --- a/client_server/client.c +++ b/client_server/client.c @@ -1,11 +1,11 @@ -// Write CPP code here -#include -#include -#include -#include +// Write CPP code here +#include +#include +#include +#include #include #include -#include +#include #define MAX 80 #define PORT 8080 #define SA struct sockaddr diff --git a/client_server/server.c b/client_server/server.c index d40ada77..26c6e1bb 100644 --- a/client_server/server.c +++ b/client_server/server.c @@ -1,95 +1,101 @@ -#include -#include -#include -#include -#include +#include +#include #include -#include -#include -#define MAX 80 -#define PORT 8080 -#define SA struct sockaddr - -// Function designed for chat between client and server. -void func(int sockfd) -{ - char buff[MAX]; - int n; - // infinite loop for chat - for (;;) { - bzero(buff, MAX); - - // read the message from client and copy it in buffer - read(sockfd, buff, sizeof(buff)); - // print buffer which contains the client contents - printf("From client: %s\t To client : ", buff); - bzero(buff, MAX); - n = 0; - // copy server message in the buffer - while ((buff[n++] = getchar()) != '\n') - ; - - // and send that buffer to client - write(sockfd, buff, sizeof(buff)); - - // if msg contains "Exit" then server exit and chat ended. - if (strncmp("exit", buff, 4) == 0) { - printf("Server Exit...\n"); - break; - } - } -} - -// Driver function -int main() -{ - int sockfd, connfd, len; - struct sockaddr_in servaddr, cli; - - // socket create and verification - sockfd = socket(AF_INET, SOCK_STREAM, 0); - if (sockfd == -1) { - printf("socket creation failed...\n"); - exit(0); - } +#include +#include +#include +#include +#include +#define MAX 80 +#define PORT 8080 +#define SA struct sockaddr + +// Function designed for chat between client and server. +void func(int sockfd) +{ + char buff[MAX]; + int n; + // infinite loop for chat + for (;;) + { + bzero(buff, MAX); + + // read the message from client and copy it in buffer + read(sockfd, buff, sizeof(buff)); + // print buffer which contains the client contents + printf("From client: %s\t To client : ", buff); + bzero(buff, MAX); + n = 0; + // copy server message in the buffer + while ((buff[n++] = getchar()) != '\n') + ; + + // and send that buffer to client + write(sockfd, buff, sizeof(buff)); + + // if msg contains "Exit" then server exit and chat ended. + if (strncmp("exit", buff, 4) == 0) + { + printf("Server Exit...\n"); + break; + } + } +} + +// Driver function +int main() +{ + int sockfd, connfd, len; + struct sockaddr_in servaddr, cli; + + // socket create and verification + sockfd = socket(AF_INET, SOCK_STREAM, 0); + if (sockfd == -1) + { + printf("socket creation failed...\n"); + exit(0); + } else - printf("Socket successfully created..\n"); - bzero(&servaddr, sizeof(servaddr)); - - // assign IP, PORT - servaddr.sin_family = AF_INET; - servaddr.sin_addr.s_addr = htonl(INADDR_ANY); - servaddr.sin_port = htons(PORT); - - // Binding newly created socket to given IP and verification - if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) { - printf("socket bind failed...\n"); - exit(0); - } + printf("Socket successfully created..\n"); + bzero(&servaddr, sizeof(servaddr)); + + // assign IP, PORT + servaddr.sin_family = AF_INET; + servaddr.sin_addr.s_addr = htonl(INADDR_ANY); + servaddr.sin_port = htons(PORT); + + // Binding newly created socket to given IP and verification + if ((bind(sockfd, (SA *)&servaddr, sizeof(servaddr))) != 0) + { + printf("socket bind failed...\n"); + exit(0); + } else - printf("Socket successfully binded..\n"); - - // Now server is ready to listen and verification - if ((listen(sockfd, 5)) != 0) { - printf("Listen failed...\n"); - exit(0); - } + printf("Socket successfully binded..\n"); + + // Now server is ready to listen and verification + if ((listen(sockfd, 5)) != 0) + { + printf("Listen failed...\n"); + exit(0); + } else - printf("Server listening..\n"); - len = sizeof(cli); - - // Accept the data packet from client and verification - connfd = accept(sockfd, (SA*)&cli, &len); - if (connfd < 0) { - printf("server acccept failed...\n"); - exit(0); - } + printf("Server listening..\n"); + len = sizeof(cli); + + // Accept the data packet from client and verification + connfd = accept(sockfd, (SA *)&cli, &len); + if (connfd < 0) + { + printf("server acccept failed...\n"); + exit(0); + } else - printf("server acccept the client...\n"); - - // Function for chatting between client and server - func(connfd); - - // After chatting close the socket - close(sockfd); -} + printf("server acccept the client...\n"); + + // Function for chatting between client and server + func(connfd); + + // After chatting close the socket + close(sockfd); +} diff --git a/conversions/binary_to_decimal.c b/conversions/binary_to_decimal.c index 81a382ed..f29037ad 100644 --- a/conversions/binary_to_decimal.c +++ b/conversions/binary_to_decimal.c @@ -1,25 +1,26 @@ /** * Modified 07/12/2017, Kyler Smith - * + * */ #include -int main() { +int main() +{ - int remainder, number = 0, decimal_number = 0, temp = 1; - printf("/n Enter any binary number= "); - scanf("%d", &number); + int remainder, number = 0, decimal_number = 0, temp = 1; + printf("/n Enter any binary number= "); + scanf("%d", &number); - // Iterate over the number until the end. - while(number > 0) { - - remainder = number % 10; - number = number / 10; - decimal_number += remainder * temp; - temp = temp*2; //used as power of 2 - - } + // Iterate over the number until the end. + while (number > 0) + { - printf("%d\n", decimal_number); + remainder = number % 10; + number = number / 10; + decimal_number += remainder * temp; + temp = temp * 2; // used as power of 2 + } + + printf("%d\n", decimal_number); } diff --git a/conversions/binary_to_hexadecimal.c b/conversions/binary_to_hexadecimal.c index 44d89429..12cec711 100644 --- a/conversions/binary_to_hexadecimal.c +++ b/conversions/binary_to_hexadecimal.c @@ -1,12 +1,12 @@ /* - * C Program to Convert Binary to Hexadecimal + * C Program to Convert Binary to Hexadecimal */ #include - + int main() { long int binary, hexa = 0, i = 1, remainder; - + printf("Enter the binary number: "); scanf("%ld", &binary); while (binary != 0) diff --git a/conversions/binary_to_octal.c b/conversions/binary_to_octal.c index 1b85eff7..d56d82ae 100644 --- a/conversions/binary_to_octal.c +++ b/conversions/binary_to_octal.c @@ -1,14 +1,14 @@ // Binary number to octal number conversion -#include +#include -//Function that returns the last three digits +// Function that returns the last three digits int three_digits(int n) { - int r, d = 0, p=1; + int r, d = 0, p = 1; - for(int i=0; i<3; i++) + for (int i = 0; i < 3; i++) { - r = n%10; + r = n % 10; d += r * p; p *= 10; n /= 10; @@ -18,24 +18,26 @@ int three_digits(int n) int main(void) { - int binary_num, d=0, base=1, remainder, td, res=0, ord=1; + int binary_num, d = 0, base = 1, remainder, td, res = 0, ord = 1; printf("Enter the binary no: "); scanf("%d", &binary_num); - while(binary_num > 0) + while (binary_num > 0) { - if(binary_num > 111) //Checking if binary number is greater than three digits + if (binary_num > + 111) // Checking if binary number is greater than three digits td = three_digits(binary_num); - else td = binary_num; + else + td = binary_num; binary_num /= 1000; - d = 0, base =1; + d = 0, base = 1; // Converting the last three digits to decimal - while(td > 0) + while (td > 0) { remainder = td % 10; td /= 10; diff --git a/conversions/decimal_to_binary.c b/conversions/decimal_to_binary.c index e27d18f7..d7f68f70 100644 --- a/conversions/decimal_to_binary.c +++ b/conversions/decimal_to_binary.c @@ -17,13 +17,13 @@ int main() // for the loops int j; - int i=0; + int i = 0; printf("\t\tConverter decimal --> binary\n\n"); // reads a decimal number from the user. printf("\nenter a positive integer number: "); - scanf("%d",&inputNumber); + scanf("%d", &inputNumber); // make sure the input number is a positive integer. if (inputNumber < 0) @@ -33,7 +33,7 @@ int main() } // actual processing - while(inputNumber>0) + while (inputNumber > 0) { // computes the remainder by modulo 2 @@ -44,15 +44,14 @@ int main() bits[i] = re; i++; - } printf("\n the number in binary is: "); // iterates backwards over all bits - for(j=i-1; j>=0; j--) + for (j = i - 1; j >= 0; j--) { - printf("%d",bits[j]); + printf("%d", bits[j]); } // for the case the input number is 0 @@ -63,4 +62,3 @@ int main() return 0; } - diff --git a/conversions/decimal_to_hexa.c b/conversions/decimal_to_hexa.c index 079b8183..52648841 100644 --- a/conversions/decimal_to_hexa.c +++ b/conversions/decimal_to_hexa.c @@ -2,45 +2,50 @@ #include void decimal2Hexadecimal(long num); - -int main(){ - - long decimalnum; - - printf("Enter decimal number: "); - scanf("%ld", &decimalnum); - - decimal2Hexadecimal(decimalnum); +int main() +{ -return 0; + long decimalnum; + + printf("Enter decimal number: "); + scanf("%ld", &decimalnum); + + decimal2Hexadecimal(decimalnum); + + return 0; } -/********function for convert decimal number to hexadecimal number****************/ -void decimal2Hexadecimal(long num){ +/********function for convert decimal number to hexadecimal + * number****************/ +void decimal2Hexadecimal(long num) +{ -long decimalnum=num; -long quotient, remainder; -int i, j = 0; -char hexadecimalnum[100]; + long decimalnum = num; + long quotient, remainder; + int i, j = 0; + char hexadecimalnum[100]; quotient = decimalnum; - while (quotient != 0){ + while (quotient != 0) + { remainder = quotient % 16; - if (remainder < 10) + if (remainder < 10) hexadecimalnum[j++] = 48 + remainder; - else - hexadecimalnum[j++] = 55 + remainder; + else + hexadecimalnum[j++] = 55 + remainder; - quotient = quotient / 16;} + quotient = quotient / 16; + } // print the hexadecimal number - for (i = j; i >= 0; i--){ - printf("%c", hexadecimalnum[i]);} + for (i = j; i >= 0; i--) + { + printf("%c", hexadecimalnum[i]); + } - printf("\n"); + printf("\n"); } - diff --git a/conversions/decimal_to_octal.c b/conversions/decimal_to_octal.c index 2cc0d4c0..dfd13c2f 100644 --- a/conversions/decimal_to_octal.c +++ b/conversions/decimal_to_octal.c @@ -1,35 +1,38 @@ /*****Decimal to octal conversion*******************/ #include void decimal2Octal(long decimalnum); - -int main(){ + +int main() +{ long decimalnum; printf("Enter the decimal number: "); - scanf("%ld", &decimalnum); - + scanf("%ld", &decimalnum); + decimal2Octal(decimalnum); -return 0; + return 0; } - -/********function for convert decimal numbers to octal numbers************/ -void decimal2Octal(long decimalnum){ - long remainder, quotient; + +/********function for convert decimal numbers to octal numbers************/ +void decimal2Octal(long decimalnum) +{ + long remainder, quotient; int octalNumber[100], i = 1, j; quotient = decimalnum; - while (quotient != 0){ - octalNumber[i++] = quotient % 8; + while (quotient != 0) + { + octalNumber[i++] = quotient % 8; quotient = quotient / 8; - } + } for (j = i - 1; j > 0; j--) printf("%d", octalNumber[j]); - printf("\n"); + printf("\n"); } diff --git a/conversions/decimal_to_octal_recursion.c b/conversions/decimal_to_octal_recursion.c index a4d21b72..937ba072 100644 --- a/conversions/decimal_to_octal_recursion.c +++ b/conversions/decimal_to_octal_recursion.c @@ -1,29 +1,29 @@ -//Program to convert decimal number to octal (Using Reccursion) -//This program only works for integer decimals -//Created by Aromal Anil +// Program to convert decimal number to octal (Using Reccursion) +// This program only works for integer decimals +// Created by Aromal Anil #include int decimal_to_octal(int decimal) { - if ((decimal < 8) && (decimal > 0)) - { - return decimal; - } - else if (decimal == 0) - { - return 0; - } - else - { - return ((decimal_to_octal(decimal / 8) * 10) + decimal % 8); - } + if ((decimal < 8) && (decimal > 0)) + { + return decimal; + } + else if (decimal == 0) + { + return 0; + } + else + { + return ((decimal_to_octal(decimal / 8) * 10) + decimal % 8); + } } int main() { - int octalNumber, decimalNumber; - printf("\nEnter your decimal number : "); - scanf("%d", &decimalNumber); - octalNumber = decimal_to_octal(decimalNumber); - printf("\nThe octal of %d is : %d", decimalNumber, octalNumber); - return 0; + int octalNumber, decimalNumber; + printf("\nEnter your decimal number : "); + scanf("%d", &decimalNumber); + octalNumber = decimal_to_octal(decimalNumber); + printf("\nThe octal of %d is : %d", decimalNumber, octalNumber); + return 0; } diff --git a/conversions/octal_to_decimal.c b/conversions/octal_to_decimal.c index f26f7141..579cdc42 100644 --- a/conversions/octal_to_decimal.c +++ b/conversions/octal_to_decimal.c @@ -2,15 +2,15 @@ #include // Converts octal number to decimal -int convertValue(int num, int i) { - return num * pow(8, i); -} +int convertValue(int num, int i) { return num * pow(8, i); } -long long toDecimal(int octal_value) { +long long toDecimal(int octal_value) +{ int decimal_value = 0, i = 0; - while (octal_value) { + while (octal_value) + { // Extracts right-most digit and then multiplies by 8^i decimal_value += convertValue(octal_value % 10, i++); @@ -22,7 +22,8 @@ long long toDecimal(int octal_value) { return decimal_value; } -int main() { +int main() +{ printf("Enter octal value: "); diff --git a/conversions/to_decimal.c b/conversions/to_decimal.c index 3697e464..28bd3ca6 100644 --- a/conversions/to_decimal.c +++ b/conversions/to_decimal.c @@ -2,39 +2,43 @@ * convert from any base to decimal */ -#include #include +#include -int main(void) { - int base, i, j; - char number[100]; - unsigned long decimal = 0; - - printf("Enter the base: "); - scanf("%d", &base); - printf("Enter the number: "); - scanf("%s", &number[0]); - - for (i = 0; number[i] != '\0'; i++) { - if (isdigit(number[i])) - number[i] -= '0'; - else if (isupper(number[i])) - number[i] -= 'A' - 10; - else if (islower(number[i])) - number[i] -= 'a' - 10; - else - number[i] = base + 1; - - if (number[i] >= base){ - printf("invalid number\n"); - return 0; - } - } - - for (j = 0; j < i; j++) { - decimal *= base; - decimal += number[j]; - } - - printf("%lu\n", decimal); +int main(void) +{ + int base, i, j; + char number[100]; + unsigned long decimal = 0; + + printf("Enter the base: "); + scanf("%d", &base); + printf("Enter the number: "); + scanf("%s", &number[0]); + + for (i = 0; number[i] != '\0'; i++) + { + if (isdigit(number[i])) + number[i] -= '0'; + else if (isupper(number[i])) + number[i] -= 'A' - 10; + else if (islower(number[i])) + number[i] -= 'a' - 10; + else + number[i] = base + 1; + + if (number[i] >= base) + { + printf("invalid number\n"); + return 0; + } + } + + for (j = 0; j < i; j++) + { + decimal *= base; + decimal += number[j]; + } + + printf("%lu\n", decimal); } diff --git a/data_structures/Array/CArray.c b/data_structures/Array/CArray.c index ea71ec10..65ac943e 100644 --- a/data_structures/Array/CArray.c +++ b/data_structures/Array/CArray.c @@ -13,243 +13,276 @@ * */ - /* - Return Codes +/* +Return Codes - -1 - Array Erased - 0 - Success - 1 - Invalid Position - 2 - Position already initialized (use update function) - 3 - Position not initialized (use insert function) - 4 - Position already empty - 5 - Array is full +-1 - Array Erased +0 - Success +1 - Invalid Position +2 - Position already initialized (use update function) +3 - Position not initialized (use insert function) +4 - Position already empty +5 - Array is full - */ +*/ +#include "CArray.h" #include #include #include -#include "CArray.h" void swap(CArray *array, int position1, int position2); -CArray * getCArray(int size) +CArray *getCArray(int size) { - CArray *array = (CArray *) malloc(sizeof(CArray)); - array->array = (int *) malloc(sizeof(int) * size); - array->size = size; - int i; - for (i = 0; i < size; i++) { - array->array[i] = 0; - } - return array; + CArray *array = (CArray *)malloc(sizeof(CArray)); + array->array = (int *)malloc(sizeof(int) * size); + array->size = size; + int i; + for (i = 0; i < size; i++) + { + array->array[i] = 0; + } + return array; } int insertValueCArray(CArray *array, int position, int value) { - if (position >= 0 && position < array->size) { - if (array->array[position] == 0) { - array->array[position] = value; - return SUCCESS; - } - else return POSITION_INIT; - } - return INVALID_POSITION; + if (position >= 0 && position < array->size) + { + if (array->array[position] == 0) + { + array->array[position] = value; + return SUCCESS; + } + else + return POSITION_INIT; + } + return INVALID_POSITION; } int removeValueCArray(CArray *array, int position) { - if (position >= 0 && position < array->size) { - if (array->array[position] != 0) { - array->array[position] = 0; - } - else return POSITION_EMPTY; - } - return INVALID_POSITION; + if (position >= 0 && position < array->size) + { + if (array->array[position] != 0) + { + array->array[position] = 0; + } + else + return POSITION_EMPTY; + } + return INVALID_POSITION; } int pushValueCArray(CArray *array, int value) { - int i; - int ok = 0; - for (i = 0; i < array->size; i++) { - if (array->array[i] == 0) { - array->array[i] = value; - ok = 1; - break; - } - } - if (ok == 1) return SUCCESS; - else return ARRAY_FULL; + int i; + int ok = 0; + for (i = 0; i < array->size; i++) + { + if (array->array[i] == 0) + { + array->array[i] = value; + ok = 1; + break; + } + } + if (ok == 1) + return SUCCESS; + else + return ARRAY_FULL; } int updateValueCArray(CArray *array, int position, int value) { - if (position >= 0 && position < array->size) { - if (array->array[position] != 0) { + if (position >= 0 && position < array->size) + { + if (array->array[position] != 0) + { + } - } - - else return POSITION_NOT_INIT; - } - return INVALID_POSITION; + else + return POSITION_NOT_INIT; + } + return INVALID_POSITION; } int eraseCArray(CArray *array) { - int i; - for (i = 0; i < array->size; i++) { - array->array[i] = 0; - } - return 0; + int i; + for (i = 0; i < array->size; i++) + { + array->array[i] = 0; + } + return 0; } int switchValuesCArray(CArray *array, int position1, int position2) { - if (position1 >= 0 && position1 < array->size - && position2 >= 0 && position2 < array->size) { - int temp = array->array[position1]; - array->array[position1] = array->array[position2]; - array->array[position2] = temp; - } - return INVALID_POSITION; + if (position1 >= 0 && position1 < array->size && position2 >= 0 && + position2 < array->size) + { + int temp = array->array[position1]; + array->array[position1] = array->array[position2]; + array->array[position2] = temp; + } + return INVALID_POSITION; } int reverseCArray(CArray *array) { - int i; - for (i = 0; i < array->size / 2; i++) { - swap(array, i, array->size - i - 1); - } - return SUCCESS; + int i; + for (i = 0; i < array->size / 2; i++) + { + swap(array, i, array->size - i - 1); + } + return SUCCESS; } int displayCArray(CArray *array) { - int i; - printf("\nC ARRAY\n"); - for (i = 0; i < array->size; i++) { - printf("%d ", array->array[i]); - } - printf("\n"); - return 0; + int i; + printf("\nC ARRAY\n"); + for (i = 0; i < array->size; i++) + { + printf("%d ", array->array[i]); + } + printf("\n"); + return 0; } int blenderCArray(CArray *array) { - srand(time(NULL) * array->size); - int i; - int total = array->size * 100; - for (i = 0; i < total; i++) { - swap(array, rand() % array->size, rand() % array->size); - } - return 0; + srand(time(NULL) * array->size); + int i; + int total = array->size * 100; + for (i = 0; i < total; i++) + { + swap(array, rand() % array->size, rand() % array->size); + } + return 0; } -CArray * getCopyCArray(CArray *arr) +CArray *getCopyCArray(CArray *arr) { - CArray *array = (CArray *)malloc(sizeof(CArray)); - array->array = (int *)malloc(sizeof(int) * arr->size); - array->size = arr->size; - int i; - for (i = 0; i < arr->size; i++) { - array->array[i] = arr->array[i]; - } - return array; + CArray *array = (CArray *)malloc(sizeof(CArray)); + array->array = (int *)malloc(sizeof(int) * arr->size); + array->size = arr->size; + int i; + for (i = 0; i < arr->size; i++) + { + array->array[i] = arr->array[i]; + } + return array; } void swap(CArray *array, int position1, int position2) { - int temp = array->array[position1]; - array->array[position1] = array->array[position2]; - array->array[position2] = temp; + int temp = array->array[position1]; + array->array[position1] = array->array[position2]; + array->array[position2] = temp; } int bubbleSortCArray(CArray *array) { - int i, j; - for (i = 0; i < array->size - 1; i++) { - for (j = 0; j < array->size - i - 1; j++) { - if (array->array[j] > array->array[j + 1]) { - swap(array, j, j + 1); - } - } - } - return 0; + int i, j; + for (i = 0; i < array->size - 1; i++) + { + for (j = 0; j < array->size - i - 1; j++) + { + if (array->array[j] > array->array[j + 1]) + { + swap(array, j, j + 1); + } + } + } + return 0; } int selectionSortCArray(CArray *array) { - int i, j, min; - for (i = 0; i < array->size - 1; i++) { - min = i; - for (j = i + 1; j < array->size; j++) - if (array->array[j] < array->array[min]) min = j; - swap(array, min, i); - } - return 0; + int i, j, min; + for (i = 0; i < array->size - 1; i++) + { + min = i; + for (j = i + 1; j < array->size; j++) + if (array->array[j] < array->array[min]) + min = j; + swap(array, min, i); + } + return 0; } int insertionSortCArray(CArray *array) { - int i, j, num; - for (i = 1; i < array->size; i++) { - num = array->array[i]; - j = i - 1; - while (j >= 0 && array->array[j] > num) - { - array->array[j + 1] = array->array[j]; - j--; - } - array->array[j + 1] = num; - } - return 0; + int i, j, num; + for (i = 1; i < array->size; i++) + { + num = array->array[i]; + j = i - 1; + while (j >= 0 && array->array[j] > num) + { + array->array[j + 1] = array->array[j]; + j--; + } + array->array[j + 1] = num; + } + return 0; } int valueOcurranceCArray(CArray *array, int value) { - int i, total = 0; - for (i = 0; i < array->size; i++) { - if (array->array[i] == value) total++; - } - return total; + int i, total = 0; + for (i = 0; i < array->size; i++) + { + if (array->array[i] == value) + total++; + } + return total; } -CArray * valuePositionsCArray(CArray *array, int value) +CArray *valuePositionsCArray(CArray *array, int value) { - int i, j = 0; - int total = valueOcurranceCArray(array, value); - CArray *resultArray = getCArray(total); - for (i = 0; i < array->size; i++) { - if (array->array[i] == value) { - // Hopefully this won't overflow - resultArray->array[j] = i; - j++; - } - } - return resultArray; + int i, j = 0; + int total = valueOcurranceCArray(array, value); + CArray *resultArray = getCArray(total); + for (i = 0; i < array->size; i++) + { + if (array->array[i] == value) + { + // Hopefully this won't overflow + resultArray->array[j] = i; + j++; + } + } + return resultArray; } int findMinCArray(CArray *array) { - int i; - int min = array->array[0]; - for (i = 1; i < array->size; i++) { - if (array->array[i] < min) { - min = array->array[i]; - } - } - return min; + int i; + int min = array->array[0]; + for (i = 1; i < array->size; i++) + { + if (array->array[i] < min) + { + min = array->array[i]; + } + } + return min; } int findMaxCArray(CArray *array) { - int i; - int max = array->array[0]; - for (i = 1; i < array->size; i++) { - if (array->array[i] > max) { - max = array->array[i]; - } - } - return max; + int i; + int max = array->array[0]; + for (i = 1; i < array->size; i++) + { + if (array->array[i] > max) + { + max = array->array[i]; + } + } + return max; } diff --git a/data_structures/Array/CArray.h b/data_structures/Array/CArray.h index d85f161a..24fa2d85 100644 --- a/data_structures/Array/CArray.h +++ b/data_structures/Array/CArray.h @@ -16,68 +16,69 @@ #pragma once #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif - #define ARRAY_ERASED -1 - #define SUCCESS 0 - #define INVALID_POSITION 1 - #define POSITION_INIT 2 - #define POSITION_NOT_INIT 3 - #define POSITION_EMPTY 4 - #define ARRAY_FULL 5 +#define ARRAY_ERASED -1 +#define SUCCESS 0 +#define INVALID_POSITION 1 +#define POSITION_INIT 2 +#define POSITION_NOT_INIT 3 +#define POSITION_EMPTY 4 +#define ARRAY_FULL 5 - typedef struct CArray { - int *array; - int size; - } CArray; + typedef struct CArray + { + int *array; + int size; + } CArray; - // +-------------------------------------+ - // | Returns array | - // +-------------------------------------+ - CArray * getCArray(int size); - CArray * getCopyCArray(CArray *array); + // +-------------------------------------+ + // | Returns array | + // +-------------------------------------+ + CArray *getCArray(int size); + CArray *getCopyCArray(CArray *array); - // +-------------------------------------+ - // | Input / Output | - // +-------------------------------------+ - int insertValueCArray(CArray *array, int position, int value); - int removeValueCArray(CArray *array, int position); - int pushValueCArray(CArray *array, int value); - int updateValueCArray(CArray *array, int position, int value); + // +-------------------------------------+ + // | Input / Output | + // +-------------------------------------+ + int insertValueCArray(CArray *array, int position, int value); + int removeValueCArray(CArray *array, int position); + int pushValueCArray(CArray *array, int value); + int updateValueCArray(CArray *array, int position, int value); - // +-------------------------------------+ - // | Erase | - // +-------------------------------------+ - int eraseCArray(CArray *array); + // +-------------------------------------+ + // | Erase | + // +-------------------------------------+ + int eraseCArray(CArray *array); - // +-------------------------------------+ - // | Switching | - // +-------------------------------------+ - int switchValuesCArray(CArray *array, int position1, int position2); - int reverseCArray(CArray *array); + // +-------------------------------------+ + // | Switching | + // +-------------------------------------+ + int switchValuesCArray(CArray *array, int position1, int position2); + int reverseCArray(CArray *array); - // +-------------------------------------+ - // | Sorting | - // +-------------------------------------+ - int bubbleSortCArray(CArray *array); - int selectionSortCArray(CArray *array); - int insertionSortCArray(CArray *array); - int blenderCArray(CArray *array); + // +-------------------------------------+ + // | Sorting | + // +-------------------------------------+ + int bubbleSortCArray(CArray *array); + int selectionSortCArray(CArray *array); + int insertionSortCArray(CArray *array); + int blenderCArray(CArray *array); - // +-------------------------------------+ - // | Searching | - // +-------------------------------------+ - int valueOcurranceCArray(CArray *array, int value); - CArray * valuePositionsCArray(CArray *array, int value); - int findMaxCArray(CArray *array); - int findMinCArray(CArray *array); + // +-------------------------------------+ + // | Searching | + // +-------------------------------------+ + int valueOcurranceCArray(CArray *array, int value); + CArray *valuePositionsCArray(CArray *array, int value); + int findMaxCArray(CArray *array); + int findMinCArray(CArray *array); - // +-------------------------------------+ - // | Display | - // +-------------------------------------+ - int displayCArray(CArray *array); - + // +-------------------------------------+ + // | Display | + // +-------------------------------------+ + int displayCArray(CArray *array); #ifdef __cplusplus } diff --git a/data_structures/Array/CArrayTests.c b/data_structures/Array/CArrayTests.c index d7bec0fa..18875c75 100644 --- a/data_structures/Array/CArrayTests.c +++ b/data_structures/Array/CArrayTests.c @@ -13,140 +13,148 @@ * */ +#include "CArray.h" #include #include #include -#include "CArray.h" int CArrayTests() { - printf("\n"); - printf(" +-------------------------------------+\n"); - printf(" | |\n"); - printf(" | C Array |\n"); - printf(" | |\n"); - printf(" +-------------------------------------+\n"); - printf("\n"); + printf("\n"); + printf(" +-------------------------------------+\n"); + printf(" | |\n"); + printf(" | C Array |\n"); + printf(" | |\n"); + printf(" +-------------------------------------+\n"); + printf("\n"); - CArray *array = getCArray(10); + CArray *array = getCArray(10); - int i; - for (i = 0; i < array->size; i++) { - insertValueCArray(array, i, i+1); - } - printf("Entered array is:\n"); - displayCArray(array); - printf("\nCode: %d\n", pushValueCArray(array, 11)); // 5 + int i; + for (i = 0; i < array->size; i++) + { + insertValueCArray(array, i, i + 1); + } + printf("Entered array is:\n"); + displayCArray(array); + printf("\nCode: %d\n", pushValueCArray(array, 11)); // 5 - for (i = 0; i < array->size; i++) { - removeValueCArray(array, i); - } - - displayCArray(array); + for (i = 0; i < array->size; i++) + { + removeValueCArray(array, i); + } - printf("\nCode: %d", removeValueCArray(array, -1)); // 1 - printf("\nCode: %d\n", insertValueCArray(array, -1, 1)); // 1 + displayCArray(array); - // Erase - for (i = 0; i < array->size; i++) { - insertValueCArray(array, i, i + 1); - } - eraseCArray(array); - displayCArray(array); // Should give all 0s + printf("\nCode: %d", removeValueCArray(array, -1)); // 1 + printf("\nCode: %d\n", insertValueCArray(array, -1, 1)); // 1 - // Switching - CArray *arr = getCArray(13); - for (i = 0; i < arr->size; i++) { - insertValueCArray(arr, i, i + 1); - } - displayCArray(arr); - for (i = 0; i < arr->size / 2; i++) { - switchValuesCArray(arr, i, arr->size - i - 1); - } + // Erase + for (i = 0; i < array->size; i++) + { + insertValueCArray(array, i, i + 1); + } + eraseCArray(array); + displayCArray(array); // Should give all 0s - displayCArray(arr); + // Switching + CArray *arr = getCArray(13); + for (i = 0; i < arr->size; i++) + { + insertValueCArray(arr, i, i + 1); + } + displayCArray(arr); + for (i = 0; i < arr->size / 2; i++) + { + switchValuesCArray(arr, i, arr->size - i - 1); + } - // Or simply... - reverseCArray(arr); + displayCArray(arr); - displayCArray(arr); - - // Sorting - srand(time(NULL)); - CArray *barray = getCArray(20); - for (i = 0; i < barray->size; i++) { - insertValueCArray(barray, i, rand()); - } - CArray *carray = getCopyCArray(barray); - CArray *darray = getCopyCArray(barray); - printf("\nNot sorted Array:"); - displayCArray(barray); + // Or simply... + reverseCArray(arr); - printf("\nBubble Sort:"); - clock_t begin1 = clock(); - // Timing bubble sort - bubbleSortCArray(barray); - clock_t end1 = clock(); - double time_spent1 = (double)(end1 - begin1) / CLOCKS_PER_SEC; - displayCArray(barray); + displayCArray(arr); - printf("\nSelection Sort:"); - clock_t begin2 = clock(); - // Timing selection sort - selectionSortCArray(carray); - clock_t end2 = clock(); - double time_spent2 = (double)(end2 - begin2) / CLOCKS_PER_SEC; - displayCArray(carray); + // Sorting + srand(time(NULL)); + CArray *barray = getCArray(20); + for (i = 0; i < barray->size; i++) + { + insertValueCArray(barray, i, rand()); + } + CArray *carray = getCopyCArray(barray); + CArray *darray = getCopyCArray(barray); + printf("\nNot sorted Array:"); + displayCArray(barray); - printf("\nInsertion Sort:"); - clock_t begin3 = clock(); - // Timing insertion sort - insertionSortCArray(darray); - clock_t end3 = clock(); - double time_spent3 = (double)(end3 - begin3) / CLOCKS_PER_SEC; - displayCArray(carray); + printf("\nBubble Sort:"); + clock_t begin1 = clock(); + // Timing bubble sort + bubbleSortCArray(barray); + clock_t end1 = clock(); + double time_spent1 = (double)(end1 - begin1) / CLOCKS_PER_SEC; + displayCArray(barray); - // Descending order - reverseCArray(barray); - // displayCArray(barray); + printf("\nSelection Sort:"); + clock_t begin2 = clock(); + // Timing selection sort + selectionSortCArray(carray); + clock_t end2 = clock(); + double time_spent2 = (double)(end2 - begin2) / CLOCKS_PER_SEC; + displayCArray(carray); -// printf("\nBlender:"); -// blenderCArray(barray); -// displayCArray(barray); + printf("\nInsertion Sort:"); + clock_t begin3 = clock(); + // Timing insertion sort + insertionSortCArray(darray); + clock_t end3 = clock(); + double time_spent3 = (double)(end3 - begin3) / CLOCKS_PER_SEC; + displayCArray(carray); - printf("\nTotal time spent for bubble sort: %lf seconds", time_spent1); - printf("\nTotal time spent for selection sort: %lf seconds", time_spent2); - printf("\nTotal time spent for insertion sort: %lf seconds", time_spent3); + // Descending order + reverseCArray(barray); + // displayCArray(barray); - // Searching - CArray *aarray = getCArray(1000); - for (i = 0; i < aarray->size; i++) { - insertValueCArray(aarray, i, rand() % 100); - } + // printf("\nBlender:"); + // blenderCArray(barray); + // displayCArray(barray); - int j = 24; - printf("\nOccurrences of the number %d in the array: %d", j, - valueOcurranceCArray(aarray, j)); - printf("\nAnd its positions:\n"); - CArray *positions = valuePositionsCArray(aarray, j); - displayCArray(positions); - // This should all give value of j - printf("\nAll %d s", j); - for (i = 0; i < positions->size; i++) { - printf("\nPosition %d has a value of %d", - positions->array[i], aarray->array[positions->array[i]]); - } - printf("\nThe list has a minimum value of %d and a maximum value of %d", - findMinCArray(aarray), findMaxCArray(aarray)); - insertionSortCArray(aarray); - // displayCArray(aarray); + printf("\nTotal time spent for bubble sort: %lf seconds", time_spent1); + printf("\nTotal time spent for selection sort: %lf seconds", time_spent2); + printf("\nTotal time spent for insertion sort: %lf seconds", time_spent3); - free(arr); - free(array); - free(aarray); - free(barray); - free(carray); - free(darray); - printf("\n"); - return 0; + // Searching + CArray *aarray = getCArray(1000); + for (i = 0; i < aarray->size; i++) + { + insertValueCArray(aarray, i, rand() % 100); + } + + int j = 24; + printf("\nOccurrences of the number %d in the array: %d", j, + valueOcurranceCArray(aarray, j)); + printf("\nAnd its positions:\n"); + CArray *positions = valuePositionsCArray(aarray, j); + displayCArray(positions); + // This should all give value of j + printf("\nAll %d s", j); + for (i = 0; i < positions->size; i++) + { + printf("\nPosition %d has a value of %d", positions->array[i], + aarray->array[positions->array[i]]); + } + printf("\nThe list has a minimum value of %d and a maximum value of %d", + findMinCArray(aarray), findMaxCArray(aarray)); + insertionSortCArray(aarray); + // displayCArray(aarray); + + free(arr); + free(array); + free(aarray); + free(barray); + free(carray); + free(darray); + printf("\n"); + return 0; } diff --git a/data_structures/binary_trees/avl.c b/data_structures/binary_trees/avl.c index d7ec01d5..f3110dae 100644 --- a/data_structures/binary_trees/avl.c +++ b/data_structures/binary_trees/avl.c @@ -3,429 +3,422 @@ struct AVLnode { - int key; - struct AVLnode *left; - struct AVLnode *right; - int height; + int key; + struct AVLnode *left; + struct AVLnode *right; + int height; }; typedef struct AVLnode avlNode; -int max(int a, int b) -{ - return (a > b)? a : b; -} +int max(int a, int b) { return (a > b) ? a : b; } avlNode *newNode(int key) { - avlNode *node = (avlNode*)malloc(sizeof(avlNode)); + avlNode *node = (avlNode *)malloc(sizeof(avlNode)); - if(node == NULL) - printf("!! Out of Space !!\n"); - else - { - node->key = key; - node->left = NULL; - node->right = NULL; - node->height = 0; - } + if (node == NULL) + printf("!! Out of Space !!\n"); + else + { + node->key = key; + node->left = NULL; + node->right = NULL; + node->height = 0; + } - return node; + return node; } int nodeHeight(avlNode *node) { - if(node == NULL) - return -1; - else - return(node->height); + if (node == NULL) + return -1; + else + return (node->height); } int heightDiff(avlNode *node) { - if(node == NULL) - return 0; - else - return(nodeHeight(node->left) - nodeHeight(node->right)); + if (node == NULL) + return 0; + else + return (nodeHeight(node->left) - nodeHeight(node->right)); } /* Returns the node with min key in the left subtree*/ avlNode *minNode(avlNode *node) { - avlNode *temp = node; + avlNode *temp = node; - while(temp->left != NULL) - temp = temp->left; + while (temp->left != NULL) + temp = temp->left; - return temp; + return temp; } void printAVL(avlNode *node, int level) { - int i; - if(node!=NULL) - { - printAVL(node->right, level+1); - printf("\n\n"); + int i; + if (node != NULL) + { + printAVL(node->right, level + 1); + printf("\n\n"); - for(i=0; ikey); + printf("%d", node->key); - printAVL(node->left, level+1); - } + printAVL(node->left, level + 1); + } } avlNode *rightRotate(avlNode *z) { - avlNode *y = z->left; - avlNode *T3 = y->right; + avlNode *y = z->left; + avlNode *T3 = y->right; - y->right = z; - z->left = T3; + y->right = z; + z->left = T3; - z->height = (max(nodeHeight(z->left), nodeHeight(z->right)) + 1); - y->height = (max(nodeHeight(y->left), nodeHeight(y->right)) + 1); + z->height = (max(nodeHeight(z->left), nodeHeight(z->right)) + 1); + y->height = (max(nodeHeight(y->left), nodeHeight(y->right)) + 1); - return y; + return y; } avlNode *leftRotate(avlNode *z) { - avlNode *y = z->right; - avlNode *T3 = y->left; + avlNode *y = z->right; + avlNode *T3 = y->left; - y->left = z; - z->right = T3; + y->left = z; + z->right = T3; - z->height = (max(nodeHeight(z->left), nodeHeight(z->right)) + 1); - y->height = (max(nodeHeight(y->left), nodeHeight(y->right)) + 1); + z->height = (max(nodeHeight(z->left), nodeHeight(z->right)) + 1); + y->height = (max(nodeHeight(y->left), nodeHeight(y->right)) + 1); - return y; + return y; } avlNode *LeftRightRotate(avlNode *z) { - z->left = leftRotate(z->left); + z->left = leftRotate(z->left); - return (rightRotate(z)); + return (rightRotate(z)); } avlNode *RightLeftRotate(avlNode *z) { - z->right = rightRotate(z->right); + z->right = rightRotate(z->right); - return (leftRotate(z)); + return (leftRotate(z)); } avlNode *insert(avlNode *node, int key) { - if(node == NULL) - return (newNode(key)); + if (node == NULL) + return (newNode(key)); - /*Binary Search Tree insertion*/ + /*Binary Search Tree insertion*/ - if(key < node->key) - node->left = insert(node->left, key); /*Recursive insertion in L subtree*/ - else if(key > node->key) - node->right = insert(node->right, key); /*Recursive insertion in R subtree*/ + if (key < node->key) + node->left = + insert(node->left, key); /*Recursive insertion in L subtree*/ + else if (key > node->key) + node->right = + insert(node->right, key); /*Recursive insertion in R subtree*/ - /* Node Height as per the AVL formula*/ - node->height = (max(nodeHeight(node->left), nodeHeight(node->right)) + 1); + /* Node Height as per the AVL formula*/ + node->height = (max(nodeHeight(node->left), nodeHeight(node->right)) + 1); + /*Checking for the balance condition*/ + int balance = heightDiff(node); - /*Checking for the balance condition*/ - int balance = heightDiff(node); + /*Left Left */ + if (balance > 1 && key < (node->left->key)) + return rightRotate(node); - /*Left Left */ - if(balance>1 && key < (node->left->key)) - return rightRotate(node); + /*Right Right */ + if (balance < -1 && key > (node->right->key)) + return leftRotate(node); - /*Right Right */ - if(balance<-1 && key > (node->right->key)) - return leftRotate(node); + /*Left Right */ + if (balance > 1 && key > (node->left->key)) + { + node = LeftRightRotate(node); + } - /*Left Right */ - if (balance>1 && key > (node->left->key)) - { - node = LeftRightRotate(node); - } - - /*Right Left */ - if (balance<-1 && key < (node->right->key)) - { - node = RightLeftRotate(node); - } - - return node; + /*Right Left */ + if (balance < -1 && key < (node->right->key)) + { + node = RightLeftRotate(node); + } + return node; } -avlNode *delete(avlNode *node, int queryNum) +avlNode *delete (avlNode *node, int queryNum) { - if(node == NULL) - return node; + if (node == NULL) + return node; - if(queryNum < node->key) - node->left = delete(node->left, queryNum); /*Recursive deletion in L subtree*/ - else if(queryNum > node->key) - node->right = delete(node->right, queryNum); /*Recursive deletion in R subtree*/ - else - { - /*Single or No Child*/ - if((node->left == NULL) || (node->right==NULL)) - { - avlNode *temp = node->left ? - node->left : - node->right; + if (queryNum < node->key) + node->left = + delete (node->left, queryNum); /*Recursive deletion in L subtree*/ + else if (queryNum > node->key) + node->right = + delete (node->right, queryNum); /*Recursive deletion in R subtree*/ + else + { + /*Single or No Child*/ + if ((node->left == NULL) || (node->right == NULL)) + { + avlNode *temp = node->left ? node->left : node->right; - /* No Child*/ - if(temp == NULL) - { - temp = node; - node = NULL; - } - else /*Single Child : copy data to the parent*/ - *node = *temp; + /* No Child*/ + if (temp == NULL) + { + temp = node; + node = NULL; + } + else /*Single Child : copy data to the parent*/ + *node = *temp; - free(temp); - } - else - { - /*Two Child*/ + free(temp); + } + else + { + /*Two Child*/ - /*Get the smallest key in the R subtree*/ - avlNode *temp = minNode(node->right); - node->key = temp->key; /*Copy that to the root*/ - node->right = delete(node->right, temp->key); /*Delete the smallest in the R subtree.*/ - } - } + /*Get the smallest key in the R subtree*/ + avlNode *temp = minNode(node->right); + node->key = temp->key; /*Copy that to the root*/ + node->right = + delete (node->right, + temp->key); /*Delete the smallest in the R subtree.*/ + } + } - /*single node in tree*/ - if(node == NULL) - return node; + /*single node in tree*/ + if (node == NULL) + return node; + /*Update height*/ + node->height = (max(nodeHeight(node->left), nodeHeight(node->right)) + 1); - /*Update height*/ - node->height = (max(nodeHeight(node->left), nodeHeight(node->right)) + 1); + int balance = heightDiff(node); - int balance = heightDiff(node); + /*Left Left */ + if ((balance > 1) && (heightDiff(node->left) >= 0)) + return rightRotate(node); - /*Left Left */ - if((balance>1) && (heightDiff(node->left) >= 0)) - return rightRotate(node); + /*Left Right */ + if ((balance > 1) && (heightDiff(node->left) < 0)) + { + node = LeftRightRotate(node); + } - /*Left Right */ - if ((balance>1) && (heightDiff(node->left) < 0)) - { - node = LeftRightRotate(node); - } + /*Right Right */ + if ((balance < -1) && (heightDiff(node->right) >= 0)) + return leftRotate(node); - /*Right Right */ - if((balance<-1) && (heightDiff(node->right) >= 0)) - return leftRotate(node); - - /*Right Left */ - if ((balance<-1) && (heightDiff(node->right) < 0)) - { - node = RightLeftRotate(node); - } - - return node; + /*Right Left */ + if ((balance < -1) && (heightDiff(node->right) < 0)) + { + node = RightLeftRotate(node); + } + return node; } avlNode *findNode(avlNode *node, int queryNum) { - if(node!=NULL) - { - if(queryNum < node->key) - node = findNode(node->left, queryNum); - else if(queryNum > node->key) - node = findNode(node->right, queryNum); - } + if (node != NULL) + { + if (queryNum < node->key) + node = findNode(node->left, queryNum); + else if (queryNum > node->key) + node = findNode(node->right, queryNum); + } - return node; + return node; } void printPreOrder(avlNode *node) { - if(node == NULL) - return; + if (node == NULL) + return; - printf(" %d ", (node->key)); - printPreOrder(node->left); - printPreOrder(node->right); + printf(" %d ", (node->key)); + printPreOrder(node->left); + printPreOrder(node->right); } void printInOrder(avlNode *node) { - if(node == NULL) - return; - printInOrder(node->left); - printf(" %d ", (node->key)); - printInOrder(node->right); + if (node == NULL) + return; + printInOrder(node->left); + printf(" %d ", (node->key)); + printInOrder(node->right); } void printPostOrder(avlNode *node) { - if(node == NULL) - return; - printPostOrder(node->left); - printPostOrder(node->right); - printf(" %d ", (node->key)); + if (node == NULL) + return; + printPostOrder(node->left); + printPostOrder(node->right); + printf(" %d ", (node->key)); } int main() { - int choice; - int flag=1; - int insertNum; - int queryNum; + int choice; + int flag = 1; + int insertNum; + int queryNum; - avlNode *root = NULL; - avlNode *tempNode; + avlNode *root = NULL; + avlNode *tempNode; - while(flag == 1) - { - printf("\n\nEnter the Step to Run : \n"); + while (flag == 1) + { + printf("\n\nEnter the Step to Run : \n"); - printf("\t1: Insert a node into AVL tree\n"); - printf("\t2: Delete a node in AVL tree\n"); - printf("\t3: Search a node into AVL tree\n"); - printf("\t4: printPreOrder (Ro L R) Tree\n"); - printf("\t5: printInOrder (L Ro R) Tree\n"); - printf("\t6: printPostOrder (L R Ro) Tree\n"); - printf("\t7: printAVL Tree\n"); + printf("\t1: Insert a node into AVL tree\n"); + printf("\t2: Delete a node in AVL tree\n"); + printf("\t3: Search a node into AVL tree\n"); + printf("\t4: printPreOrder (Ro L R) Tree\n"); + printf("\t5: printInOrder (L Ro R) Tree\n"); + printf("\t6: printPostOrder (L R Ro) Tree\n"); + printf("\t7: printAVL Tree\n"); - printf("\t0: EXIT\n"); - scanf("%d", &choice); + printf("\t0: EXIT\n"); + scanf("%d", &choice); - switch(choice) - { - case 0: - { - flag=0; - printf("\n\t\tExiting, Thank You !!\n"); - break; - } + switch (choice) + { + case 0: + { + flag = 0; + printf("\n\t\tExiting, Thank You !!\n"); + break; + } - case 1: - { + case 1: + { - printf("\n\tEnter the Number to insert: "); - scanf("%d", &insertNum); + printf("\n\tEnter the Number to insert: "); + scanf("%d", &insertNum); - tempNode = findNode(root, insertNum); + tempNode = findNode(root, insertNum); - if(tempNode!=NULL) - printf("\n\t %d Already exists in the tree\n", insertNum); - else - { - printf("\n\tPrinting AVL Tree\n"); - printAVL(root, 1); - printf("\n"); + if (tempNode != NULL) + printf("\n\t %d Already exists in the tree\n", insertNum); + else + { + printf("\n\tPrinting AVL Tree\n"); + printAVL(root, 1); + printf("\n"); - root = insert(root, insertNum); - printf("\n\tPrinting AVL Tree\n"); - printAVL(root, 1); - printf("\n"); - } + root = insert(root, insertNum); + printf("\n\tPrinting AVL Tree\n"); + printAVL(root, 1); + printf("\n"); + } - break; - } + break; + } - case 2: - { - printf("\n\tEnter the Number to Delete: "); - scanf("%d", &queryNum); + case 2: + { + printf("\n\tEnter the Number to Delete: "); + scanf("%d", &queryNum); - tempNode = findNode(root, queryNum); + tempNode = findNode(root, queryNum); - if(tempNode==NULL) - printf("\n\t %d Does not exist in the tree\n", queryNum); - else - { - printf("\n\tPrinting AVL Tree\n"); - printAVL(root, 1); - printf("\n"); - root = delete(root, queryNum); + if (tempNode == NULL) + printf("\n\t %d Does not exist in the tree\n", queryNum); + else + { + printf("\n\tPrinting AVL Tree\n"); + printAVL(root, 1); + printf("\n"); + root = delete (root, queryNum); - printf("\n\tPrinting AVL Tree\n"); - printAVL(root, 1); - printf("\n"); - } + printf("\n\tPrinting AVL Tree\n"); + printAVL(root, 1); + printf("\n"); + } - break; - } + break; + } - case 3: - { - printf("\n\tEnter the Number to Search: "); - scanf("%d", &queryNum); + case 3: + { + printf("\n\tEnter the Number to Search: "); + scanf("%d", &queryNum); - tempNode = findNode(root, queryNum); + tempNode = findNode(root, queryNum); + if (tempNode == NULL) + printf("\n\t %d : Not Found\n", queryNum); + else + { + printf("\n\t %d : Found at height %d \n", queryNum, + tempNode->height); - if(tempNode == NULL) - printf("\n\t %d : Not Found\n", queryNum); - else - { - printf("\n\t %d : Found at height %d \n", queryNum, tempNode->height); + printf("\n\tPrinting AVL Tree\n"); + printAVL(root, 1); + printf("\n"); + } - printf("\n\tPrinting AVL Tree\n"); - printAVL(root, 1); - printf("\n"); - } + break; + } - break; - } + case 4: + { + printf("\nPrinting Tree preOrder\n"); + printPreOrder(root); - case 4: - { - printf("\nPrinting Tree preOrder\n"); - printPreOrder(root); + break; + } - break; - } + case 5: + { + printf("\nPrinting Tree inOrder\n"); + printInOrder(root); - case 5: - { - printf("\nPrinting Tree inOrder\n"); - printInOrder(root); + break; + } - break; - } + case 6: + { + printf("\nPrinting Tree PostOrder\n"); + printPostOrder(root); - case 6: - { - printf("\nPrinting Tree PostOrder\n"); - printPostOrder(root); + break; + } - break; - } + case 7: + { + printf("\nPrinting AVL Tree\n"); + printAVL(root, 1); - case 7: - { - printf("\nPrinting AVL Tree\n"); - printAVL(root, 1); + break; + } - break; - } + default: + { + flag = 0; + printf("\n\t\tExiting, Thank You !!\n"); + break; + } + } + } - default: - { - flag=0; - printf("\n\t\tExiting, Thank You !!\n"); - break; - } - - } - - - } - - - return 0; + return 0; } diff --git a/data_structures/binary_trees/binary_search_tree.c b/data_structures/binary_trees/binary_search_tree.c index f86ad9c3..8981f0ca 100644 --- a/data_structures/binary_trees/binary_search_tree.c +++ b/data_structures/binary_trees/binary_search_tree.c @@ -1,7 +1,8 @@ #include #include -/* A basic unbalanced binary search tree implementation in C, with the following functionalities implemented: +/* A basic unbalanced binary search tree implementation in C, with the following + functionalities implemented: - Insertion - Deletion - Search by key value @@ -9,198 +10,237 @@ */ // Node, the basic data structure in the tree -typedef struct node{ +typedef struct node +{ // left child - struct node* left; + struct node *left; - // right child - struct node* right; + // right child + struct node *right; - // data of the node - int data; + // data of the node + int data; } node; -// The node constructor, which receives the key value input and returns a node pointer -node* newNode(int data){ +// The node constructor, which receives the key value input and returns a node +// pointer +node *newNode(int data) +{ // creates a slug - node* tmp = (node*)malloc(sizeof(node)); + node *tmp = (node *)malloc(sizeof(node)); - // initializes the slug - tmp->data = data; - tmp->left = NULL; - tmp->right = NULL; + // initializes the slug + tmp->data = data; + tmp->left = NULL; + tmp->right = NULL; - return tmp; + return tmp; } // Insertion procedure, which inserts the input key in a new node in the tree -node* insert(node* root, int data){ - // If the root of the subtree is null, insert key here - if (root == NULL) - root = newNode(data); - // If it isn't null and the input key is greater than the root key, insert in the right leaf - else if (data > root->data) - root->right = insert(root->right, data); - // If it isn't null and the input key is lower than the root key, insert in the left leaf - else if (data < root->data) - root->left = insert(root->left, data); - // Returns the modified tree - return root; +node *insert(node *root, int data) +{ + // If the root of the subtree is null, insert key here + if (root == NULL) + root = newNode(data); + // If it isn't null and the input key is greater than the root key, insert + // in the right leaf + else if (data > root->data) + root->right = insert(root->right, data); + // If it isn't null and the input key is lower than the root key, insert in + // the left leaf + else if (data < root->data) + root->left = insert(root->left, data); + // Returns the modified tree + return root; } // Utilitary procedure to find the greatest key in the left subtree -node* getMax(node* root){ - // If there's no leaf to the right, then this is the maximum key value - if (root->right == NULL) - return root; - else - root->right = getMax(root->right); +node *getMax(node *root) +{ + // If there's no leaf to the right, then this is the maximum key value + if (root->right == NULL) + return root; + else + root->right = getMax(root->right); } -// Deletion procedure, which searches for the input key in the tree and removes it if present -node* delete(node* root, int data){ - // If the root is null, nothing to be done - if (root == NULL) - return root; - // If the input key is greater than the root's, search in the right subtree - else if (data > root->data) - root->right = delete(root->right, data); - // If the input key is lower than the root's, search in the left subtree - else if (data < root->data) - root->left = delete(root->left, data); - // If the input key matches the root's, check the following cases - // termination condition - else if (data == root->data){ - // Case 1: the root has no leaves, remove the node - if ((root->left == NULL) && (root->right == NULL)){ - free(root); - return NULL; - } - // Case 2: the root has one leaf, make the leaf the new root and remove the old root - else if (root->left == NULL){ - node* tmp = root; - root = root->right; - free(tmp); - return root; - } - else if (root->right == NULL){ - node* tmp = root; - root = root->left; - free(tmp); - return root; - } - // Case 3: the root has 2 leaves, find the greatest key in the left subtree and switch with the root's - else { +// Deletion procedure, which searches for the input key in the tree and removes +// it if present +node *delete (node *root, int data) +{ + // If the root is null, nothing to be done + if (root == NULL) + return root; + // If the input key is greater than the root's, search in the right subtree + else if (data > root->data) + root->right = delete (root->right, data); + // If the input key is lower than the root's, search in the left subtree + else if (data < root->data) + root->left = delete (root->left, data); + // If the input key matches the root's, check the following cases + // termination condition + else if (data == root->data) + { + // Case 1: the root has no leaves, remove the node + if ((root->left == NULL) && (root->right == NULL)) + { + free(root); + return NULL; + } + // Case 2: the root has one leaf, make the leaf the new root and remove + // the old root + else if (root->left == NULL) + { + node *tmp = root; + root = root->right; + free(tmp); + return root; + } + else if (root->right == NULL) + { + node *tmp = root; + root = root->left; + free(tmp); + return root; + } + // Case 3: the root has 2 leaves, find the greatest key in the left + // subtree and switch with the root's + else + { // finds the biggest node in the left branch. - node* tmp = getMax(root->left); + node *tmp = getMax(root->left); - // sets the data of this node equal to the data of the biggest node (lefts) - root->data = tmp->data; - root->left = delete(root->left, tmp->data); - } - } - return root; + // sets the data of this node equal to the data of the biggest node + // (lefts) + root->data = tmp->data; + root->left = delete (root->left, tmp->data); + } + } + return root; } -// Search procedure, which looks for the input key in the tree and returns 1 if it's present or 0 if it's not in the tree -int find(node* root, int data){ - // If the root is null, the key's not present - if (root == NULL) - return 0; - // If the input key is greater than the root's, search in the right subtree - else if (data > root->data) - return find(root->right, data); - // If the input key is lower than the root's, search in the left subtree - else if (data < root->data) - return find(root->left, data); - // If the input and the root key match, return 1 - else if (data == root->data) - return 1; +// Search procedure, which looks for the input key in the tree and returns 1 if +// it's present or 0 if it's not in the tree +int find(node *root, int data) +{ + // If the root is null, the key's not present + if (root == NULL) + return 0; + // If the input key is greater than the root's, search in the right subtree + else if (data > root->data) + return find(root->right, data); + // If the input key is lower than the root's, search in the left subtree + else if (data < root->data) + return find(root->left, data); + // If the input and the root key match, return 1 + else if (data == root->data) + return 1; } // Utilitary procedure to measure the height of the binary tree -int height(node* root){ - // If the root is null, this is the bottom of the tree (height 0) - if (root == NULL) - return 0; - else{ - // Get the height from both left and right subtrees to check which is the greatest - int right_h = height(root->right); - int left_h = height(root->left); +int height(node *root) +{ + // If the root is null, this is the bottom of the tree (height 0) + if (root == NULL) + return 0; + else + { + // Get the height from both left and right subtrees to check which is + // the greatest + int right_h = height(root->right); + int left_h = height(root->left); - // The final height is the height of the greatest subtree(left or right) plus 1(which is the root's level) - if (right_h > left_h) - return (right_h + 1); - else - return (left_h + 1); - } + // The final height is the height of the greatest subtree(left or right) + // plus 1(which is the root's level) + if (right_h > left_h) + return (right_h + 1); + else + return (left_h + 1); + } } // Utilitary procedure to free all nodes in a tree -void purge(node* root){ - if (root != NULL){ - if (root->left != NULL) - purge(root->left); - if (root->right != NULL) - purge(root->right); - free(root); - } +void purge(node *root) +{ + if (root != NULL) + { + if (root->left != NULL) + purge(root->left); + if (root->right != NULL) + purge(root->right); + free(root); + } } -// Traversal procedure to list the current keys in the tree in order of value (from the left to the right) -void inOrder(node* root){ - if(root != NULL){ - inOrder(root->left); - printf("\t[ %d ]\t", root->data); - inOrder(root->right); - } +// Traversal procedure to list the current keys in the tree in order of value +// (from the left to the right) +void inOrder(node *root) +{ + if (root != NULL) + { + inOrder(root->left); + printf("\t[ %d ]\t", root->data); + inOrder(root->right); + } } -void main(){ +void main() +{ // this reference don't change. // only the tree changes. - node* root = NULL; - int opt = -1; - int data = 0; + node *root = NULL; + int opt = -1; + int data = 0; // event-loop. - while (opt != 0){ - printf("\n\n[1] Insert Node\n[2] Delete Node\n[3] Find a Node\n[4] Get current Height\n[5] Print Tree in Crescent Order\n[0] Quit\n"); - scanf("%d",&opt); // reads the choice of the user + while (opt != 0) + { + printf("\n\n[1] Insert Node\n[2] Delete Node\n[3] Find a Node\n[4] Get " + "current Height\n[5] Print Tree in Crescent Order\n[0] Quit\n"); + scanf("%d", &opt); // reads the choice of the user // processes the choice - switch(opt){ - case 1: printf("Enter the new node's value:\n"); - scanf("%d",&data); - root = insert(root,data); - break; + switch (opt) + { + case 1: + printf("Enter the new node's value:\n"); + scanf("%d", &data); + root = insert(root, data); + break; - case 2: printf("Enter the value to be removed:\n"); - if (root != NULL){ - scanf("%d",&data); - root = delete(root,data); - } - else - printf("Tree is already empty!\n"); - break; + case 2: + printf("Enter the value to be removed:\n"); + if (root != NULL) + { + scanf("%d", &data); + root = delete (root, data); + } + else + printf("Tree is already empty!\n"); + break; - case 3: printf("Enter the searched value:\n"); - scanf("%d",&data); - find(root,data) ? printf("The value is in the tree.\n") : printf("The value is not in the tree.\n"); - break; + case 3: + printf("Enter the searched value:\n"); + scanf("%d", &data); + find(root, data) ? printf("The value is in the tree.\n") + : printf("The value is not in the tree.\n"); + break; - case 4: printf("Current height of the tree is: %d\n", height(root)); - break; + case 4: + printf("Current height of the tree is: %d\n", height(root)); + break; - case 5: inOrder(root); - break; - } - } + case 5: + inOrder(root); + break; + } + } // deletes the tree from the heap. - purge(root); + purge(root); } diff --git a/data_structures/binary_trees/create_node.c b/data_structures/binary_trees/create_node.c index f1f59e4d..fda592d8 100644 --- a/data_structures/binary_trees/create_node.c +++ b/data_structures/binary_trees/create_node.c @@ -1,5 +1,5 @@ /* Includes structure for a node and a newNode() function which - can be used to create a new node in the tree. + can be used to create a new node in the tree. It is assumed that the data in nodes will be an integer, though function can be modified according to the data type, easily. */ @@ -35,5 +35,5 @@ int main(void) nameOfNode->leftNode and so on. */ - return 0; + return 0; } \ No newline at end of file diff --git a/data_structures/binary_trees/recursive_traversals.c b/data_structures/binary_trees/recursive_traversals.c index aff56255..175e16d3 100644 --- a/data_structures/binary_trees/recursive_traversals.c +++ b/data_structures/binary_trees/recursive_traversals.c @@ -7,7 +7,7 @@ void inOrderTraversal(struct node *node) { - if(node == NULL) //if tree is empty + if (node == NULL) // if tree is empty return; inOrderTraversal(node->leftNode); @@ -17,7 +17,7 @@ void inOrderTraversal(struct node *node) void preOrderTraversal(struct node *node) { - if(node == NULL) //if tree is empty + if (node == NULL) // if tree is empty return; printf("\t%d\t", node->data); @@ -27,12 +27,12 @@ void preOrderTraversal(struct node *node) void postOrderTraversal(struct node *node) { - if(node == NULL) //if tree is empty + if (node == NULL) // if tree is empty return; postOrderTraversal(node->leftNode); postOrderTraversal(node->rightNode); - printf("\t%d\t",node->data); + printf("\t%d\t", node->data); } int main(void) @@ -41,5 +41,5 @@ int main(void) function with a pointer to the root node. */ - return 0; + return 0; } \ No newline at end of file diff --git a/data_structures/binary_trees/redBlackTree.c b/data_structures/binary_trees/redBlackTree.c index 8d7d7b06..e66895b7 100644 --- a/data_structures/binary_trees/redBlackTree.c +++ b/data_structures/binary_trees/redBlackTree.c @@ -1,18 +1,20 @@ +#include #include #include -#include -typedef struct node{ +typedef struct node +{ int val; - struct node* par; - struct node* left; - struct node* right; + struct node *par; + struct node *left; + struct node *right; int color; -}Node; +} Node; // Create a new node -Node* newNode(int val, Node* par){ - Node* create = (Node*)(malloc(sizeof(Node))); +Node *newNode(int val, Node *par) +{ + Node *create = (Node *)(malloc(sizeof(Node))); create->val = val; create->par = par; create->left = NULL; @@ -21,30 +23,37 @@ Node* newNode(int val, Node* par){ } // Check if the node is the leaf -int isLeaf(Node* n){ - if(n->left == NULL && n->right == NULL){ +int isLeaf(Node *n) +{ + if (n->left == NULL && n->right == NULL) + { return 1; } return 0; } // Left Rotate -Node* leftRotate(Node* node){ - Node* parent = node->par; - Node* grandParent = parent->par; +Node *leftRotate(Node *node) +{ + Node *parent = node->par; + Node *grandParent = parent->par; parent->right = node->left; - if(node->left != NULL){ + if (node->left != NULL) + { node->left->par = parent; } node->par = grandParent; parent->par = node; node->left = parent; - if(grandParent != NULL){ - if(grandParent->right == parent){ + if (grandParent != NULL) + { + if (grandParent->right == parent) + { grandParent->right = node; } - else{ + else + { grandParent->left = node; } } @@ -52,73 +61,86 @@ Node* leftRotate(Node* node){ } // Right Rotate -Node* rightRotate(Node* node){ - Node* parent = node->par; - Node* grandParent = parent->par; +Node *rightRotate(Node *node) +{ + Node *parent = node->par; + Node *grandParent = parent->par; parent->left = node->right; - if(node->right != NULL){ + if (node->right != NULL) + { node->right->par = parent; } node->par = grandParent; parent->par = node; node->right = parent; - if(grandParent != NULL){ - if(grandParent->right == parent){ + if (grandParent != NULL) + { + if (grandParent->right == parent) + { grandParent->right = node; } - else{ + else + { grandParent->left = node; } } return node; } - // Check the node after the insertion step -void checkNode(Node* node){ +void checkNode(Node *node) +{ // If the node is the root - if(node == NULL || node->par == NULL){ + if (node == NULL || node->par == NULL) + { return; } - Node* child = node; - //If it is a black node or its parent is a black node - if(node->color == 0 || (node->par)->color == 0){ + Node *child = node; + // If it is a black node or its parent is a black node + if (node->color == 0 || (node->par)->color == 0) + { // Dont Do Anything return; } // Both parent and child are red // Check For Uncle - Node* parent = node->par; - Node* grandParent = parent->par; + Node *parent = node->par; + Node *grandParent = parent->par; // If grandParent is NULL, then parent is the root. // Just make the root black. - if(grandParent == NULL){ + if (grandParent == NULL) + { parent->color = 0; return; } - // If both the children of the grandParent are red - if(grandParent->right != NULL && (grandParent->right)->color == 1 && grandParent->left != NULL && (grandParent->left)->color == 1){ + if (grandParent->right != NULL && (grandParent->right)->color == 1 && + grandParent->left != NULL && (grandParent->left)->color == 1) + { // Make the grandParent red and both of its children black (grandParent->right)->color = 0; (grandParent->left)->color = 0; grandParent->color = 1; return; } - else{ + else + { // The only option left is rotation. - Node* greatGrandParent = grandParent->par; + Node *greatGrandParent = grandParent->par; // Right Case - if(grandParent->right == parent){ - //Right Right Case - if(parent->right == node){ + if (grandParent->right == parent) + { + // Right Right Case + if (parent->right == node) + { grandParent->right = parent->left; - if(parent->left != NULL){ + if (parent->left != NULL) + { (parent->left)->par = grandParent; } parent->left = grandParent; @@ -126,11 +148,15 @@ void checkNode(Node* node){ // Attach to existing Tree; parent->par = greatGrandParent; - if(greatGrandParent != NULL){ - if(greatGrandParent->left != NULL && greatGrandParent->left == grandParent){ + if (greatGrandParent != NULL) + { + if (greatGrandParent->left != NULL && + greatGrandParent->left == grandParent) + { greatGrandParent->left = parent; } - else{ + else + { greatGrandParent->right = parent; } } @@ -139,18 +165,21 @@ void checkNode(Node* node){ parent->color = 0; grandParent->color = 1; } - else{ // Right Left Case + else + { // Right Left Case // First step -> Parent Child Rotation parent->left = child->right; - if(child->right != NULL){ + if (child->right != NULL) + { (child->right)->par = parent; } child->right = parent; parent->par = child; - + // Second step -> Child and GrandParent Rotation grandParent->right = child->left; - if(child->left != NULL){ + if (child->left != NULL) + { (child->left)->par = grandParent; } child->left = grandParent; @@ -158,11 +187,15 @@ void checkNode(Node* node){ // Attach to the existing tree child->par = greatGrandParent; - if(greatGrandParent != NULL){ - if(greatGrandParent->left != NULL && greatGrandParent->left == grandParent){ + if (greatGrandParent != NULL) + { + if (greatGrandParent->left != NULL && + greatGrandParent->left == grandParent) + { greatGrandParent->left = child; } - else{ + else + { greatGrandParent->right = child; } } @@ -172,11 +205,14 @@ void checkNode(Node* node){ grandParent->color = 1; } } - else{ // Left Case - //Left Left Case - if(parent->left == node){ + else + { // Left Case + // Left Left Case + if (parent->left == node) + { grandParent->left = parent->right; - if(parent->right != NULL){ + if (parent->right != NULL) + { (parent->right)->par = grandParent; } parent->right = grandParent; @@ -184,11 +220,15 @@ void checkNode(Node* node){ // Attach to existing Tree; parent->par = greatGrandParent; - if(greatGrandParent != NULL){ - if(greatGrandParent->left != NULL && greatGrandParent->left == grandParent){ + if (greatGrandParent != NULL) + { + if (greatGrandParent->left != NULL && + greatGrandParent->left == grandParent) + { greatGrandParent->left = parent; } - else{ + else + { greatGrandParent->right = parent; } } @@ -197,19 +237,22 @@ void checkNode(Node* node){ parent->color = 0; grandParent->color = 1; } - else{ //Left Right Case - + else + { // Left Right Case + // First step -> Parent Child Rotation parent->right = child->left; - if(child->left != NULL){ + if (child->left != NULL) + { (child->left)->par = parent; } child->left = parent; parent->par = child; - + // Second step -> Child and GrandParent Rotation grandParent->left = child->right; - if(child->right != NULL){ + if (child->right != NULL) + { (child->right)->par = grandParent; } child->right = grandParent; @@ -217,11 +260,15 @@ void checkNode(Node* node){ // Attach to the existing tree child->par = greatGrandParent; - if(greatGrandParent != NULL){ - if(greatGrandParent->left != NULL && greatGrandParent->left == grandParent){ + if (greatGrandParent != NULL) + { + if (greatGrandParent->left != NULL && + greatGrandParent->left == grandParent) + { greatGrandParent->left = child; } - else{ + else + { greatGrandParent->right = child; } } @@ -235,71 +282,88 @@ void checkNode(Node* node){ } // To insert a node in the existing tree -void insertNode(int val, Node** root){ - Node* buffRoot = *root; - while(buffRoot){ - if(buffRoot->val > val){ +void insertNode(int val, Node **root) +{ + Node *buffRoot = *root; + while (buffRoot) + { + if (buffRoot->val > val) + { // Go left - if(buffRoot->left != NULL){ + if (buffRoot->left != NULL) + { buffRoot = buffRoot->left; } - else{ - //Insert The Node - Node* toInsert = newNode(val, buffRoot); + else + { + // Insert The Node + Node *toInsert = newNode(val, buffRoot); buffRoot->left = toInsert; buffRoot = toInsert; - //Check For Double Red Problems + // Check For Double Red Problems break; } } - else{ + else + { // Go right - if(buffRoot->right != NULL){ + if (buffRoot->right != NULL) + { buffRoot = buffRoot->right; } - else{ - //Insert The Node - Node* toInsert = newNode(val, buffRoot); + else + { + // Insert The Node + Node *toInsert = newNode(val, buffRoot); buffRoot->right = toInsert; buffRoot = toInsert; - //Check For Double Red Problems + // Check For Double Red Problems break; } } } - - while(buffRoot != *root){ + while (buffRoot != *root) + { checkNode(buffRoot); - if(buffRoot->par == NULL){ + if (buffRoot->par == NULL) + { *root = buffRoot; break; } buffRoot = buffRoot->par; - if(buffRoot == *root){ + if (buffRoot == *root) + { buffRoot->color = 0; } } } -void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){ +void checkForCase2(Node *toDelete, int delete, int fromDirection, Node **root) +{ - if(toDelete == (*root)){ + if (toDelete == (*root)) + { (*root)->color = 0; return; } - if(!delete && toDelete->color == 1){ - if(!fromDirection){ - if(toDelete->right != NULL){ + if (!delete &&toDelete->color == 1) + { + if (!fromDirection) + { + if (toDelete->right != NULL) + { toDelete->right->color = 1; } } - else{ - if(toDelete->left != NULL){ + else + { + if (toDelete->left != NULL) + { toDelete->left->color = 1; } } @@ -307,26 +371,31 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){ return; } - // Get the sibling for further inspection - Node* sibling; - Node* parent = toDelete->par; - int locateChild = 0; // 0 if toDeleted is left of its parent else 1 - if(parent->right == toDelete){ + Node *sibling; + Node *parent = toDelete->par; + int locateChild = 0; // 0 if toDeleted is left of its parent else 1 + if (parent->right == toDelete) + { sibling = parent->left; locateChild = 1; } - else{ + else + { sibling = parent->right; } - //Case 2.1. i.e. if the any children of the sibling is red - if((sibling->right != NULL && sibling->right->color == 1) || (sibling->left != NULL && sibling->left->color == 1)){ - if(sibling->right != NULL && sibling->right->color == 1){ + // Case 2.1. i.e. if the any children of the sibling is red + if ((sibling->right != NULL && sibling->right->color == 1) || + (sibling->left != NULL && sibling->left->color == 1)) + { + if (sibling->right != NULL && sibling->right->color == 1) + { // Sibling is left and child is right. i.e. LEFT RIGHT ROTATION - if(locateChild == 1){ - + if (locateChild == 1) + { + int parColor = parent->color; // Step 1: Left rotate sibling @@ -336,7 +405,8 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){ parent = rightRotate(sibling); // Check if the root is rotated - if(parent->par == NULL){ + if (parent->par == NULL) + { *root = parent; } @@ -346,16 +416,19 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){ parent->right->color = 0; // Delete the node (present at parent->right->right) - if(delete){ - if(toDelete->left != NULL){ + if (delete) + { + if (toDelete->left != NULL) + { toDelete->left->par = parent->right; } parent->right->right = toDelete->left; free(toDelete); } - } - else{ // Sibling is right and child is also right. i.e. LEFT LEFT ROTATION + else + { // Sibling is right and child is also right. i.e. LEFT LEFT + // ROTATION int parColor = parent->color; @@ -363,7 +436,8 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){ parent = leftRotate(sibling); // Check if the root is rotated - if(parent->par == NULL){ + if (parent->par == NULL) + { *root = parent; } @@ -373,21 +447,24 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){ parent->right->color = 0; // Delete the node (present at parent->left->left) - if(delete){ - if(toDelete->right != NULL){ + if (delete) + { + if (toDelete->right != NULL) + { toDelete->right->par = parent->left; } parent->left->left = toDelete->left; free(toDelete); } - } } - else{ + else + { // Sibling is right and child is left. i.e. RIGHT LEFT ROTATION - if(locateChild == 0){ - + if (locateChild == 0) + { + int parColor = parent->color; // Step 1: Right rotate sibling @@ -400,7 +477,8 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){ parent = leftRotate(sibling); // Check if the root is rotated - if(parent->par == NULL){ + if (parent->par == NULL) + { *root = parent; } @@ -410,17 +488,19 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){ parent->right->color = 0; // Delete the node (present at parent->left->left) - if(delete){ - if(toDelete->right != NULL){ + if (delete) + { + if (toDelete->right != NULL) + { toDelete->right->par = parent->left; } parent->left->left = toDelete->right; free(toDelete); } - - } - else{ // Sibling is left and child is also left. i.e. RIGHT RIGHT ROTATION + else + { // Sibling is left and child is also left. i.e. RIGHT RIGHT + // ROTATION int parColor = parent->color; @@ -428,7 +508,8 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){ parent = rightRotate(sibling); // Check if the root is rotated - if(parent->par == NULL){ + if (parent->par == NULL) + { *root = parent; } @@ -438,33 +519,40 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){ parent->right->color = 0; // Delete the node (present at parent->right->right) - if(delete){ - if(toDelete->left != NULL){ + if (delete) + { + if (toDelete->left != NULL) + { toDelete->left->par = parent->right; } parent->right->right = toDelete->left; free(toDelete); } - } } } - else if(sibling->color == 0){ //Make the sibling red and recur for its parent + else if (sibling->color == 0) + { // Make the sibling red and recur for its parent // Recolor the sibling sibling->color = 1; // Delete if necessary - if(delete){ - if(locateChild){ + if (delete) + { + if (locateChild) + { toDelete->par->right = toDelete->left; - if(toDelete->left != NULL){ + if (toDelete->left != NULL) + { toDelete->left->par = toDelete->par; } } - else{ + else + { toDelete->par->left = toDelete->right; - if(toDelete->right != NULL){ + if (toDelete->right != NULL) + { toDelete->right->par = toDelete->par; } } @@ -472,18 +560,22 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){ checkForCase2(parent, 0, locateChild, root); } - else{ // Bring the sibling on top and apply 2.1 or 2.2 accordingly - if(locateChild){ //Right Rotate + else + { // Bring the sibling on top and apply 2.1 or 2.2 accordingly + if (locateChild) + { // Right Rotate toDelete->par->right = toDelete->left; - if(toDelete->left != NULL){ + if (toDelete->left != NULL) + { toDelete->left->par = toDelete->par; } parent = rightRotate(sibling); // Check if the root is rotated - if(parent->par == NULL){ + if (parent->par == NULL) + { *root = parent; } @@ -491,16 +583,19 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){ parent->right->color = 1; checkForCase2(parent->right, 0, 1, root); } - else{ // Left Rotate + else + { // Left Rotate toDelete->par->left = toDelete->right; - if(toDelete->right != NULL){ + if (toDelete->right != NULL) + { toDelete->right->par = toDelete->par; } parent = leftRotate(sibling); // Check if the root is rotated - if(parent->par == NULL){ + if (parent->par == NULL) + { *root = parent; } @@ -511,58 +606,71 @@ void checkForCase2(Node* toDelete, int delete, int fromDirection, Node** root){ checkForCase2(parent->left, 0, 0, root); } } - } // To delete a node from the tree -void deleteNode(int val, Node** root){ - Node* buffRoot = *root; +void deleteNode(int val, Node **root) +{ + Node *buffRoot = *root; - //Search for the element in the tree - while(1){ - - if(val == buffRoot->val){ + // Search for the element in the tree + while (1) + { + + if (val == buffRoot->val) + { // Node Found break; } - if(val > buffRoot->val){ - if(buffRoot->right != NULL){ + if (val > buffRoot->val) + { + if (buffRoot->right != NULL) + { buffRoot = buffRoot->right; } - else{ + else + { printf("Node Not Found!!!"); return; } } - else{ - if(buffRoot->left != NULL){ + else + { + if (buffRoot->left != NULL) + { buffRoot = buffRoot->left; } - else{ + else + { printf("Node Not Found!!!"); return; } } } - Node* toDelete = buffRoot; + Node *toDelete = buffRoot; // Look for the leftmost of right node or right most of left node - if(toDelete->left != NULL){ + if (toDelete->left != NULL) + { toDelete = toDelete->left; - while(toDelete->right != NULL){ + while (toDelete->right != NULL) + { toDelete = toDelete->right; } } - else if(toDelete->right != NULL){ + else if (toDelete->right != NULL) + { toDelete = toDelete->right; - while(toDelete->left != NULL){ + while (toDelete->left != NULL) + { toDelete = toDelete->left; } } - if(toDelete == *root){ + if (toDelete == *root) + { *root = NULL; return; } @@ -572,28 +680,37 @@ void deleteNode(int val, Node** root){ toDelete->val = val; // Checking for case 1 - if(toDelete->color == 1 || (toDelete->left != NULL && toDelete->left->color == 1) || (toDelete->right != NULL && toDelete->right->color == 1)){ - + if (toDelete->color == 1 || + (toDelete->left != NULL && toDelete->left->color == 1) || + (toDelete->right != NULL && toDelete->right->color == 1)) + { + // if it is a leaf - if(toDelete->left == NULL && toDelete->right == NULL){ + if (toDelete->left == NULL && toDelete->right == NULL) + { // Delete instantly - if(toDelete->par->left == toDelete){ + if (toDelete->par->left == toDelete) + { toDelete->par->left = NULL; } - else{ + else + { toDelete->par->right = NULL; } } - else{ // else its child should be red + else + { // else its child should be red // Check for the exitstence of left node - if(toDelete->left != NULL){ + if (toDelete->left != NULL) + { // The node should be right to its parent toDelete->par->right = toDelete->left; toDelete->left->par = toDelete->par; toDelete->left->color = 1; } - else{ // else the right node should be red + else + { // else the right node should be red toDelete->par->left = toDelete->right; toDelete->right->par = toDelete->par; toDelete->right->color = 1; @@ -603,76 +720,85 @@ void deleteNode(int val, Node** root){ // Remove the node from memory free(toDelete); } - else{ // Case 2 + else + { // Case 2 checkForCase2(toDelete, 1, ((toDelete->par->right == toDelete)), root); } - - - } -void printInorder(Node* root){ - if(root != NULL){ +void printInorder(Node *root) +{ + if (root != NULL) + { printInorder(root->left); printf("%d c-%d ", root->val, root->color); printInorder(root->right); } } -void checkBlack(Node* temp,int c){ - if (temp==NULL){ - printf("%d ",c); - return ; +void checkBlack(Node *temp, int c) +{ + if (temp == NULL) + { + printf("%d ", c); + return; } - if (temp->color==0){ + if (temp->color == 0) + { c++; } - checkBlack(temp->left,c); - checkBlack(temp->right,c); + checkBlack(temp->left, c); + checkBlack(temp->right, c); } -int main(){ - Node* root = NULL; +int main() +{ + Node *root = NULL; int scanValue, choice = 1; - printf("1 - Input\n2 - Delete\n3 - Inorder Traversel\n0 - Quit\n\nPlease Enter the Choice - "); + printf("1 - Input\n2 - Delete\n3 - Inorder Traversel\n0 - Quit\n\nPlease " + "Enter the Choice - "); scanf("%d", &choice); - while(choice){ - switch(choice){ - case 1: - printf("\n\nPlease Enter A Value to insert - "); - scanf("%d", &scanValue); - if(root == NULL){ - root = newNode(scanValue, NULL); - root->color = 0; - } - else{ - insertNode(scanValue, &root); - } - printf("\nSuccessfully Inserted %d in the tree\n\n", scanValue); - break; - case 2: - printf("\n\nPlease Enter A Value to Delete - "); - scanf("%d", &scanValue); - deleteNode(scanValue, &root); - printf("\nSuccessfully Inserted %d in the tree\n\n", scanValue); - break; - case 3: - printf("\nInorder Traversel - "); - printInorder(root); - printf("\n\n"); - // checkBlack(root,0); - // printf("\n"); - break; - default: - if(root != NULL){ - printf("Root - %d\n", root->val); - } + while (choice) + { + switch (choice) + { + case 1: + printf("\n\nPlease Enter A Value to insert - "); + scanf("%d", &scanValue); + if (root == NULL) + { + root = newNode(scanValue, NULL); + root->color = 0; + } + else + { + insertNode(scanValue, &root); + } + printf("\nSuccessfully Inserted %d in the tree\n\n", scanValue); + break; + case 2: + printf("\n\nPlease Enter A Value to Delete - "); + scanf("%d", &scanValue); + deleteNode(scanValue, &root); + printf("\nSuccessfully Inserted %d in the tree\n\n", scanValue); + break; + case 3: + printf("\nInorder Traversel - "); + printInorder(root); + printf("\n\n"); + // checkBlack(root,0); + // printf("\n"); + break; + default: + if (root != NULL) + { + printf("Root - %d\n", root->val); + } } - printf("1 - Input\n2 - Delete\n3 - Inorder Traversel\n0 - Quit\n\nPlease Enter the Choice - "); + printf("1 - Input\n2 - Delete\n3 - Inorder Traversel\n0 - " + "Quit\n\nPlease Enter the Choice - "); scanf("%d", &choice); } } - - // 32 12 50 53 1 2 3 4 5 6 7 8 9 diff --git a/data_structures/dictionary/dict.c b/data_structures/dictionary/dict.c index 8e8a6462..e0bc2a50 100644 --- a/data_structures/dictionary/dict.c +++ b/data_structures/dictionary/dict.c @@ -1,32 +1,30 @@ +#include "dict.h" #include #include -#include "dict.h" - /* simple constructor */ -Dictionary * create_dict(void) +Dictionary *create_dict(void) { - Dictionary * p_dic = malloc(sizeof (Dictionary)); + Dictionary *p_dic = malloc(sizeof(Dictionary)); if (p_dic) { p_dic->number_of_elements = 0; /* initializes the elemens of the array with NULL-pointer */ - for (int i = 0; i < MAXELEMENTS; i++) + for (int i = 0; i < MAXELEMENTS; i++) { p_dic->elements[i] = NULL; } return p_dic; } - else + else { printf("unable to create a dictionary\n"); return NULL; } } - /* utility function sdbm hash algorithm @@ -37,18 +35,18 @@ int get_hash(char s[]) unsigned int hash_code = 0; /* iterates over string at each character */ - for (int counter = 0; s[counter]!='\0'; counter++) + for (int counter = 0; s[counter] != '\0'; counter++) { /* actual computing of the hash code */ - hash_code = s[counter] + (hash_code << 6) + (hash_code << 16) - hash_code; + hash_code = + s[counter] + (hash_code << 6) + (hash_code << 16) - hash_code; } /* % modulo is for fitting the index in array. */ return hash_code % MAXELEMENTS; } - -int add_item_label(Dictionary * dic,char label[],void * item) +int add_item_label(Dictionary *dic, char label[], void *item) { unsigned int index = get_hash(label); @@ -57,28 +55,26 @@ int add_item_label(Dictionary * dic,char label[],void * item) { dic->elements[index] = item; return 0; - } - + } + /* error case */ - return -1; + return -1; } - -int add_item_index(Dictionary * dic , int index, void * item) +int add_item_index(Dictionary *dic, int index, void *item) { /* make sure whether this place is already given */ if (!dic->elements[index]) { dic->elements[index] = item; return 0; - } - + } + /* error case */ return -1; } - -void * get_element_label(Dictionary * dict, char s[]) +void *get_element_label(Dictionary *dict, char s[]) { int index = get_hash(s); if (dict->elements[index]) @@ -90,20 +86,15 @@ void * get_element_label(Dictionary * dict, char s[]) return NULL; } - -void * get_element_index(Dictionary * dict, int index) +void *get_element_index(Dictionary *dict, int index) { if (index >= 0 && index < MAXELEMENTS) { return dict->elements[index]; } - + printf("index out of bounds!\n"); return NULL; } - -void destroy(Dictionary * dict) -{ - free(dict); -} \ No newline at end of file +void destroy(Dictionary *dict) { free(dict); } \ No newline at end of file diff --git a/data_structures/dictionary/dict.h b/data_structures/dictionary/dict.h index 175a4dac..520b3295 100644 --- a/data_structures/dictionary/dict.h +++ b/data_structures/dictionary/dict.h @@ -1,6 +1,6 @@ /* author: Christian Bender - public interface for the dictionary. + public interface for the dictionary. The dictionary prepares space for 1000 elements. */ @@ -14,13 +14,13 @@ special data type called 'Dictionary' for generic use */ -typedef struct Dict +typedef struct Dict { - /* + /* void* array for generic use of the dictionary. there actual saves the entries. */ - void * elements[MAXELEMENTS]; + void *elements[MAXELEMENTS]; /* contains the number of elements in this dictionary */ int number_of_elements; @@ -28,41 +28,38 @@ typedef struct Dict } Dictionary; /* - create_dict: is a simple constructor for creating - a dictionary and setting up the + create_dict: is a simple constructor for creating + a dictionary and setting up the member field 'number_of_elements' and prepares the inner array 'elements' */ -Dictionary * create_dict(void); +Dictionary *create_dict(void); -/* - add_item_label: adds item (void*) to the dictionary at given label +/* + add_item_label: adds item (void*) to the dictionary at given label returns 0 if adding was sucessful otherwise -1 */ -int add_item_label(Dictionary *,char label[],void *); +int add_item_label(Dictionary *, char label[], void *); -/* - add_item_index: adds item (void*) to the dictionary at given index (int) +/* + add_item_index: adds item (void*) to the dictionary at given index (int) returns 0 if adding was sucessful otherwise -1 */ int add_item_index(Dictionary *, int index, void *); +/* + get_element: returns the element at given label +*/ +void *get_element_label(Dictionary *, char[]); /* - get_element: returns the element at given label + get_element: returns the element at given index */ -void * get_element_label(Dictionary *, char []); - +void *get_element_index(Dictionary *, int); /* - get_element: returns the element at given index -*/ -void * get_element_index(Dictionary *, int ); - -/* simple destrcutor function */ void destroy(Dictionary *); - #endif \ No newline at end of file diff --git a/data_structures/dictionary/test_program.c b/data_structures/dictionary/test_program.c index 39ba7296..dabf2e77 100644 --- a/data_structures/dictionary/test_program.c +++ b/data_structures/dictionary/test_program.c @@ -10,32 +10,32 @@ int main(void) { - Dictionary * testObj1; - Dictionary * testObj2; + Dictionary *testObj1; + Dictionary *testObj2; - int value = 28; + int value = 28; testObj1 = create_dict(); testObj2 = create_dict(); - add_item_label(testObj1,"age",&value); - add_item_label(testObj2,"name","Christian"); - + add_item_label(testObj1, "age", &value); + add_item_label(testObj2, "name", "Christian"); /* test for function add_item_label - attention: - The void* pointer must be convert into an int* pointer. + attention: + The void* pointer must be convert into an int* pointer. After that you can dereference it. */ - printf("My age is %d\n",*((int *)get_element_label(testObj1,"age"))); - printf("My name is %s\n",get_element_label(testObj2,"name")); + printf("My age is %d\n", *((int *)get_element_label(testObj1, "age"))); + printf("My name is %s\n", get_element_label(testObj2, "name")); /* test for function add_item_index */ - if (!add_item_index(testObj1,0,&value)) + if (!add_item_index(testObj1, 0, &value)) { - printf("My age at index %d is %d\n",0,*((int *)get_element_index(testObj1,0))); + printf("My age at index %d is %d\n", 0, + *((int *)get_element_index(testObj1, 0))); } /* error scenario */ diff --git a/data_structures/dynamic_array/dynamic_array.c b/data_structures/dynamic_array/dynamic_array.c index abde3204..7ecf359c 100644 --- a/data_structures/dynamic_array/dynamic_array.c +++ b/data_structures/dynamic_array/dynamic_array.c @@ -1,7 +1,7 @@ -#include -#include -#include #include "dynamic_array.h" +#include +#include +#include dynamic_array_t *init_dynamic_array() { @@ -14,8 +14,10 @@ dynamic_array_t *init_dynamic_array() void *add(dynamic_array_t *da, const void *value) { - if (da->size >= da->capacity) { - void **newItems = realloc(da->items, (da->capacity <<= 1) * sizeof(void **)); + if (da->size >= da->capacity) + { + void **newItems = + realloc(da->items, (da->capacity <<= 1) * sizeof(void **)); free(da->items); da->items = newItems; @@ -52,7 +54,8 @@ void delete (dynamic_array_t *da, const unsigned index) if (!contains(da->size, index)) return; - for (unsigned i = index; i < da->size; i++) { + for (unsigned i = index; i < da->size; i++) + { da->items[i] = da->items[i + 1]; } diff --git a/data_structures/dynamic_array/dynamic_array.h b/data_structures/dynamic_array/dynamic_array.h index 76b77924..dce4a519 100644 --- a/data_structures/dynamic_array/dynamic_array.h +++ b/data_structures/dynamic_array/dynamic_array.h @@ -3,7 +3,8 @@ #define DEFAULT_CAPACITY 1 << 4 #define INDEX_OUT_OF_BOUNDS NULL -typedef struct dynamic_array { +typedef struct dynamic_array +{ void **items; unsigned size; unsigned capacity; diff --git a/data_structures/dynamic_array/main.c b/data_structures/dynamic_array/main.c index 2d3ab9ed..9948a919 100644 --- a/data_structures/dynamic_array/main.c +++ b/data_structures/dynamic_array/main.c @@ -6,7 +6,8 @@ int main() { dynamic_array_t *da = init_dynamic_array(); - for (int i = 1; i <= 50; i++) { + for (int i = 1; i <= 50; i++) + { add(da, &i); } @@ -22,7 +23,8 @@ int main() add(da, &another_value); - for (int i = 0; i < da->size; i++) { + for (int i = 0; i < da->size; i++) + { printf("value %d\n", *(int *)get(da, i)); } diff --git a/data_structures/graphs/BFS.c b/data_structures/graphs/BFS.c index cb5d75f5..e53831b2 100644 --- a/data_structures/graphs/BFS.c +++ b/data_structures/graphs/BFS.c @@ -1,63 +1,64 @@ #include #include #define SIZE 40 -//Assume max size of graph is 40 nodes -struct queue { +// Assume max size of graph is 40 nodes +struct queue +{ int items[SIZE]; int front; int rear; }; -//Some declarations -struct queue* createQueue(); -void enqueue(struct queue* q, int); -int dequeue(struct queue* q); -void display(struct queue* q); -int isEmpty(struct queue* q); -int pollQueue(struct queue* q); +// Some declarations +struct queue *createQueue(); +void enqueue(struct queue *q, int); +int dequeue(struct queue *q); +void display(struct queue *q); +int isEmpty(struct queue *q); +int pollQueue(struct queue *q); -//Structure to create a graph node +// Structure to create a graph node struct node { int vertex; - struct node* next; + struct node *next; }; -struct node* createNode(int); +struct node *createNode(int); -//Graph data structure +// Graph data structure struct Graph { int numVertices; - struct node** adjLists; - int* visited; + struct node **adjLists; + int *visited; }; -struct Graph* createGraph(int vertices); -void addEdge(struct Graph* graph, int src, int dest); -void printGraph(struct Graph* graph); -void bfs(struct Graph* graph, int startVertex); +struct Graph *createGraph(int vertices); +void addEdge(struct Graph *graph, int src, int dest); +void printGraph(struct Graph *graph); +void bfs(struct Graph *graph, int startVertex); int main() { - int vertices,edges,source,i,src,dst; - printf("Enter the number of vertices\n"); - scanf("%d",&vertices); - struct Graph* graph = createGraph(vertices); - printf("Enter the number of edges\n"); - scanf("%d",&edges); - for(i=0; ivisited[startVertex] = 1; enqueue(q, startVertex); - printf("Breadth first traversal from vertex %d is:\n",startVertex); - - //Iterate while queue not empty - while(!isEmpty(q)){ - printf("%d ",pollQueue(q)); + printf("Breadth first traversal from vertex %d is:\n", startVertex); + + // Iterate while queue not empty + while (!isEmpty(q)) + { + printf("%d ", pollQueue(q)); int currentVertex = dequeue(q); - - struct node* temp = graph->adjLists[currentVertex]; - //Add all unvisited neighbours of current vertex to queue to be printed next - while(temp) { + + struct node *temp = graph->adjLists[currentVertex]; + // Add all unvisited neighbours of current vertex to queue to be printed + // next + while (temp) + { int adjVertex = temp->vertex; - //Only add if neighbour is unvisited - if(graph->visited[adjVertex] == 0){ + // Only add if neighbour is unvisited + if (graph->visited[adjVertex] == 0) + { graph->visited[adjVertex] = 1; enqueue(q, adjVertex); } temp = temp->next; - } + } } } -//Memory for a graph node -struct node* createNode(int v) +// Memory for a graph node +struct node *createNode(int v) { - struct node* newNode = malloc(sizeof(struct node)); + struct node *newNode = malloc(sizeof(struct node)); newNode->vertex = v; newNode->next = NULL; return newNode; } -//Allocates memory for graph data structure, in adjacency list format -struct Graph* createGraph(int vertices) +// Allocates memory for graph data structure, in adjacency list format +struct Graph *createGraph(int vertices) { - struct Graph* graph = malloc(sizeof(struct Graph)); + struct Graph *graph = malloc(sizeof(struct Graph)); graph->numVertices = vertices; - - graph->adjLists = malloc(vertices * sizeof(struct node*)); + + graph->adjLists = malloc(vertices * sizeof(struct node *)); graph->visited = malloc(vertices * sizeof(int)); - + int i; - for (i = 0; i < vertices; i++) { + for (i = 0; i < vertices; i++) + { graph->adjLists[i] = NULL; graph->visited[i] = 0; } - + return graph; } -//Adds bidirectional edge to graph -void addEdge(struct Graph* graph, int src, int dest) +// Adds bidirectional edge to graph +void addEdge(struct Graph *graph, int src, int dest) { // Add edge from src to dest - struct node* newNode = createNode(dest); + struct node *newNode = createNode(dest); newNode->next = graph->adjLists[src]; graph->adjLists[src] = newNode; - + // Add edge from dest to src; comment it out for directed graph newNode = createNode(src); newNode->next = graph->adjLists[dest]; graph->adjLists[dest] = newNode; } -//Allocates memory for our queue data structure -struct queue* createQueue() +// Allocates memory for our queue data structure +struct queue *createQueue() { - struct queue* q = malloc(sizeof(struct queue)); + struct queue *q = malloc(sizeof(struct queue)); q->front = -1; q->rear = -1; return q; } -//Checks for empty queue -int isEmpty(struct queue* q) +// Checks for empty queue +int isEmpty(struct queue *q) { - if(q->rear == -1) + if (q->rear == -1) return 1; - else + else return 0; } -//Inserts item at start of queue -void enqueue(struct queue* q, int value) +// Inserts item at start of queue +void enqueue(struct queue *q, int value) { - if(q->rear == SIZE-1) + if (q->rear == SIZE - 1) printf("\nQueue is Full!!"); - else { - if(q->front == -1) + else + { + if (q->front == -1) q->front = 0; q->rear++; q->items[q->rear] = value; } } -//Returns item at front of queue and removes it from queue -int dequeue(struct queue* q) +// Returns item at front of queue and removes it from queue +int dequeue(struct queue *q) { int item; - if(isEmpty(q)){ + if (isEmpty(q)) + { printf("Queue is empty"); item = -1; } - else{ + else + { item = q->items[q->front]; q->front++; - if(q->front > q->rear){ + if (q->front > q->rear) + { q->front = q->rear = -1; } } return item; } -//Returns element at front of queue -int pollQueue(struct queue *q) -{ - return q->items[q->front]; -} +// Returns element at front of queue +int pollQueue(struct queue *q) { return q->items[q->front]; } diff --git a/data_structures/graphs/Bellman-Ford.c b/data_structures/graphs/Bellman-Ford.c index 2d7e2a3d..48afdbf1 100644 --- a/data_structures/graphs/Bellman-Ford.c +++ b/data_structures/graphs/Bellman-Ford.c @@ -1,130 +1,140 @@ -#include -#include -#include -#include +#include +#include +#include +#include -//Structure for storing edge -struct Edge{ -int src,dst,weight; +// Structure for storing edge +struct Edge +{ + int src, dst, weight; }; -//Structure for storing a graph -struct Graph{ - int vertexNum; - int edgeNum; - struct Edge* edges; +// Structure for storing a graph +struct Graph +{ + int vertexNum; + int edgeNum; + struct Edge *edges; }; -//Constructs a graph with V vertices and E edges -void createGraph(struct Graph* G,int V,int E){ - G->vertexNum = V; - G->edgeNum = E; - G->edges = (struct Edge*) malloc(E * sizeof(struct Edge)); +// Constructs a graph with V vertices and E edges +void createGraph(struct Graph *G, int V, int E) +{ + G->vertexNum = V; + G->edgeNum = E; + G->edges = (struct Edge *)malloc(E * sizeof(struct Edge)); } -//Adds the given edge to the graph -void addEdge(struct Graph* G, int src, int dst, int weight){ - static int ind; - struct Edge newEdge; - newEdge.src = src; - newEdge.dst = dst; - newEdge.weight = weight; - G->edges[ind++]= newEdge; +// Adds the given edge to the graph +void addEdge(struct Graph *G, int src, int dst, int weight) +{ + static int ind; + struct Edge newEdge; + newEdge.src = src; + newEdge.dst = dst; + newEdge.weight = weight; + G->edges[ind++] = newEdge; } +// Utility function to find minimum distance vertex in mdist +int minDistance(int mdist[], int vset[], int V) +{ + int minVal = INT_MAX, minInd; + for (int i = 0; i < V; i++) + if (vset[i] == 0 && mdist[i] < minVal) + { + minVal = mdist[i]; + minInd = i; + } -//Utility function to find minimum distance vertex in mdist -int minDistance(int mdist[], int vset[], int V){ - int minVal = INT_MAX, minInd ; - for(int i=0; ivertexNum; - int E = graph->edgeNum; - int dist[V]; +// The main function that finds the shortest path from given source +// to all other vertices using Bellman-Ford.It also detects negative +// weight cycle +void BellmanFord(struct Graph *graph, int src) +{ + int V = graph->vertexNum; + int E = graph->edgeNum; + int dist[V]; - //Initialize distances array as INF for all except source - //Intialize source as zero - for(int i=0; iedges[j].src; - int v = graph->edges[j].dst; - int w = graph->edges[j].weight; - - if(dist[u]!=INT_MAX && dist[u] + w < dist[v]) - dist[v] = dist[u] + w; - } - - //Iterate inner loop once more to check for negative cycle - for(int j = 0; jedges[j].src; - int v = graph->edges[j].dst; - int w = graph->edges[j].weight; - - if(dist[u]!=INT_MAX && dist[u] + w < dist[v]){ - printf("Graph contains negative weight cycle. Hence, shortest distance not guaranteed."); - return; - } - } + // Calculate shortest path distance from source to all edges + // A path can contain maximum (|V|-1) edges + for (int i = 0; i <= V - 1; i++) + for (int j = 0; j < E; j++) + { + int u = graph->edges[j].src; + int v = graph->edges[j].dst; + int w = graph->edges[j].weight; - print(dist, V); - - return; + if (dist[u] != INT_MAX && dist[u] + w < dist[v]) + dist[v] = dist[u] + w; + } + + // Iterate inner loop once more to check for negative cycle + for (int j = 0; j < E; j++) + { + int u = graph->edges[j].src; + int v = graph->edges[j].dst; + int w = graph->edges[j].weight; + + if (dist[u] != INT_MAX && dist[u] + w < dist[v]) + { + printf("Graph contains negative weight cycle. Hence, shortest " + "distance not guaranteed."); + return; + } + } + + print(dist, V); + + return; } +// Driver Function +int main() +{ + int V, E, gsrc; + int src, dst, weight; + struct Graph G; + printf("Enter number of vertices: "); + scanf("%d", &V); + printf("Enter number of edges: "); + scanf("%d", &E); + createGraph(&G, V, E); + for (int i = 0; i < E; i++) + { + printf("\nEdge %d \nEnter source: ", i + 1); + scanf("%d", &src); + printf("Enter destination: "); + scanf("%d", &dst); + printf("Enter weight: "); + scanf("%d", &weight); + addEdge(&G, src, dst, weight); + } + printf("\nEnter source:"); + scanf("%d", &gsrc); + BellmanFord(&G, gsrc); - -//Driver Function -int main(){ - int V,E,gsrc; - int src,dst,weight; - struct Graph G; - printf("Enter number of vertices: "); - scanf("%d",&V); - printf("Enter number of edges: "); - scanf("%d",&E); - createGraph(&G,V,E); - for(int i=0; i #include -//A vertex of the graph +// A vertex of the graph struct node { int vertex; - struct node* next; + struct node *next; }; -//Some declarations -struct node* createNode(int v); +// Some declarations +struct node *createNode(int v); struct Graph { int numVertices; - int* visited; - struct node** adjLists; // we need int** to store a two dimensional array. Similary, we need struct node** to store an array of Linked lists + int *visited; + struct node * + *adjLists; // we need int** to store a two dimensional array. Similary, + // we need struct node** to store an array of Linked lists }; -struct Graph* createGraph(int); -void addEdge(struct Graph*, int, int); -void printGraph(struct Graph*); -void dfs(struct Graph*, int); +struct Graph *createGraph(int); +void addEdge(struct Graph *, int, int); +void printGraph(struct Graph *); +void dfs(struct Graph *, int); int main() -{ - int vertices,edges,source,i,src,dst; - printf("Enter the number of vertices\n"); - scanf("%d",&vertices); - struct Graph* graph = createGraph(vertices); - printf("Enter the number of edges\n"); - scanf("%d",&edges); - for(i=0; iadjLists[vertex]; - struct node* temp = adjList; - - //Add vertex to visited list and print it - graph->visited[vertex] = 1; - printf("%d ", vertex); - - //Recursively call the dfs function on all unvisited neighbours - while(temp!=NULL) { - int connectedVertex = temp->vertex; - if(graph->visited[connectedVertex] == 0) { - dfs(graph, connectedVertex); - } - temp = temp->next; - } -} - //Allocate memory for a node -struct node* createNode(int v) +// Recursive dfs approach +void dfs(struct Graph *graph, int vertex) { - struct node* newNode = malloc(sizeof(struct node)); + struct node *adjList = graph->adjLists[vertex]; + struct node *temp = adjList; + + // Add vertex to visited list and print it + graph->visited[vertex] = 1; + printf("%d ", vertex); + + // Recursively call the dfs function on all unvisited neighbours + while (temp != NULL) + { + int connectedVertex = temp->vertex; + if (graph->visited[connectedVertex] == 0) + { + dfs(graph, connectedVertex); + } + temp = temp->next; + } +} +// Allocate memory for a node +struct node *createNode(int v) +{ + struct node *newNode = malloc(sizeof(struct node)); newNode->vertex = v; newNode->next = NULL; return newNode; } -//Allocate memory for the entire graph structure -struct Graph* createGraph(int vertices) +// Allocate memory for the entire graph structure +struct Graph *createGraph(int vertices) { - struct Graph* graph = malloc(sizeof(struct Graph)); + struct Graph *graph = malloc(sizeof(struct Graph)); graph->numVertices = vertices; - - graph->adjLists = malloc(vertices * sizeof(struct node*)); - + + graph->adjLists = malloc(vertices * sizeof(struct node *)); + graph->visited = malloc(vertices * sizeof(int)); - + int i; - for (i = 0; i < vertices; i++) { + for (i = 0; i < vertices; i++) + { graph->adjLists[i] = NULL; graph->visited[i] = 0; } return graph; } -//Creates a bidirectional graph -void addEdge(struct Graph* graph, int src, int dest) +// Creates a bidirectional graph +void addEdge(struct Graph *graph, int src, int dest) { // Add edge from src to dest - struct node* newNode = createNode(dest); + struct node *newNode = createNode(dest); newNode->next = graph->adjLists[src]; graph->adjLists[src] = newNode; - + // Add edge from dest to src newNode = createNode(src); newNode->next = graph->adjLists[dest]; graph->adjLists[dest] = newNode; } -//Utility function to see state of graph at a given time -void printGraph(struct Graph* graph) +// Utility function to see state of graph at a given time +void printGraph(struct Graph *graph) { int v; for (v = 0; v < graph->numVertices; v++) { - struct node* temp = graph->adjLists[v]; + struct node *temp = graph->adjLists[v]; printf("\n Adjacency list of vertex %d\n ", v); while (temp) { diff --git a/data_structures/graphs/Dijkstra.c b/data_structures/graphs/Dijkstra.c index 265b33a3..6f2d1378 100644 --- a/data_structures/graphs/Dijkstra.c +++ b/data_structures/graphs/Dijkstra.c @@ -1,114 +1,121 @@ -#include -#include -#include -#include +#include +#include +#include +#include - -//Structure for storing a graph -struct Graph{ - int vertexNum; - int** edges; +// Structure for storing a graph +struct Graph +{ + int vertexNum; + int **edges; }; -//Constructs a graph with V vertices and E edges -void createGraph(struct Graph* G,int V){ - G->vertexNum = V; - G->edges =(int**) malloc(V * sizeof(int*)); - for(int i=0; iedges[i] = (int*) malloc(V * sizeof(int)); - for(int j=0; jedges[i][j] = INT_MAX; - G->edges[i][i] = 0; - } +// Constructs a graph with V vertices and E edges +void createGraph(struct Graph *G, int V) +{ + G->vertexNum = V; + G->edges = (int **)malloc(V * sizeof(int *)); + for (int i = 0; i < V; i++) + { + G->edges[i] = (int *)malloc(V * sizeof(int)); + for (int j = 0; j < V; j++) + G->edges[i][j] = INT_MAX; + G->edges[i][i] = 0; + } } -//Adds the given edge to the graph -void addEdge(struct Graph* G, int src, int dst, int weight){ - G->edges[src][dst] = weight; +// Adds the given edge to the graph +void addEdge(struct Graph *G, int src, int dst, int weight) +{ + G->edges[src][dst] = weight; } +// Utility function to find minimum distance vertex in mdist +int minDistance(int mdist[], int vset[], int V) +{ + int minVal = INT_MAX, minInd; + for (int i = 0; i < V; i++) + if (vset[i] == 0 && mdist[i] < minVal) + { + minVal = mdist[i]; + minInd = i; + } -//Utility function to find minimum distance vertex in mdist -int minDistance(int mdist[], int vset[], int V){ - int minVal = INT_MAX, minInd ; - for(int i=0; ivertexNum; - int mdist[V]; //Stores updated distances to vertex - int vset[V]; // vset[i] is true if the vertex i included - // in the shortest path tree +// The main function that finds the shortest path from given source +// to all other vertices using Dijkstra's Algorithm.It doesn't work on negative +// weights +void Dijkstra(struct Graph *graph, int src) +{ + int V = graph->vertexNum; + int mdist[V]; // Stores updated distances to vertex + int vset[V]; // vset[i] is true if the vertex i included + // in the shortest path tree - //Initialise mdist and vset. Set distance of source as zero - for(int i=0; iedges[u][v]!=INT_MAX && mdist[u] + graph->edges[u][v] < mdist[v]) - mdist[v] = mdist[u] + graph->edges[u][v]; - - } - } + // Initialise mdist and vset. Set distance of source as zero + for (int i = 0; i < V; i++) + mdist[i] = INT_MAX, vset[i] = 0; - print(mdist, V); - - return; + mdist[src] = 0; + + // iterate to find shortest path + for (int count = 0; count < V - 1; count++) + { + int u = minDistance(mdist, vset, V); + vset[u] = 1; + + for (int v = 0; v < V; v++) + { + if (!vset[v] && graph->edges[u][v] != INT_MAX && + mdist[u] + graph->edges[u][v] < mdist[v]) + mdist[v] = mdist[u] + graph->edges[u][v]; + } + } + + print(mdist, V); + + return; } +// Driver Function +int main() +{ + int V, E, gsrc; + int src, dst, weight; + struct Graph G; + printf("Enter number of vertices: "); + scanf("%d", &V); + printf("Enter number of edges: "); + scanf("%d", &E); + createGraph(&G, V); + for (int i = 0; i < E; i++) + { + printf("\nEdge %d \nEnter source: ", i + 1); + scanf("%d", &src); + printf("Enter destination: "); + scanf("%d", &dst); + printf("Enter weight: "); + scanf("%d", &weight); + addEdge(&G, src, dst, weight); + } + printf("\nEnter source:"); + scanf("%d", &gsrc); + Dijkstra(&G, gsrc); - -//Driver Function -int main(){ - int V,E,gsrc; - int src,dst,weight; - struct Graph G; - printf("Enter number of vertices: "); - scanf("%d",&V); - printf("Enter number of edges: "); - scanf("%d",&E); - createGraph(&G,V); - for(int i=0; i -#include -#include -#include +#include +#include +#include +#include - -//Structure for storing a graph -struct Graph{ - int vertexNum; - int** edges; +// Structure for storing a graph +struct Graph +{ + int vertexNum; + int **edges; }; -//Constructs a graph with V vertices and E edges -void createGraph(struct Graph* G,int V){ - G->vertexNum = V; - G->edges =(int**) malloc(V * sizeof(int*)); - for(int i=0; iedges[i] = (int*) malloc(V * sizeof(int)); - for(int j=0; jedges[i][j] = INT_MAX; - G->edges[i][i] = 0; - } +// Constructs a graph with V vertices and E edges +void createGraph(struct Graph *G, int V) +{ + G->vertexNum = V; + G->edges = (int **)malloc(V * sizeof(int *)); + for (int i = 0; i < V; i++) + { + G->edges[i] = (int *)malloc(V * sizeof(int)); + for (int j = 0; j < V; j++) + G->edges[i][j] = INT_MAX; + G->edges[i][i] = 0; + } } -//Adds the given edge to the graph -void addEdge(struct Graph* G, int src, int dst, int weight){ - G->edges[src][dst] = weight; +// Adds the given edge to the graph +void addEdge(struct Graph *G, int src, int dst, int weight) +{ + G->edges[src][dst] = weight; } +// Utility function to print distances +void print(int dist[], int V) +{ + printf("\nThe Distance matrix for Floyd - Warshall\n"); + for (int i = 0; i < V; i++) + { + for (int j = 0; j < V; j++) + { -//Utility function to print distances -void print(int dist[], int V){ - printf("\nThe Distance matrix for Floyd - Warshall\n"); - for(int i = 0; i < V; i++){ - for(int j=0; jvertexNum; - int dist[V][V]; - - //Initialise distance array - for(int i=0; iedges[i][j]; - - - //Calculate distances - for(int k=0; kvertexNum; + int dist[V][V]; - for(int i=0; iedges[i][j]; - for(int j=0; j -#include #include +#include -typedef struct GraphRep { - int **edges; // adjacency matrix - int nV; // #vertices - int nE; // #edges +typedef struct GraphRep +{ + int **edges; // adjacency matrix + int nV; // #vertices + int nE; // #edges } GraphRep; -Graph newGraph(int V) { - assert(V >= 0); - int i; +Graph newGraph(int V) +{ + assert(V >= 0); + int i; - Graph g = malloc(sizeof(GraphRep)); - assert(g != NULL); - g->nV = V; - g->nE = 0; + Graph g = malloc(sizeof(GraphRep)); + assert(g != NULL); + g->nV = V; + g->nE = 0; - // allocate memory for each row - g->edges = malloc(V * sizeof(int *)); - assert(g->edges != NULL); - // allocate memory for each column and initialise with 0 - for (i = 0; i < V; i++) { - g->edges[i] = calloc(V, sizeof(int)); - assert(g->edges[i] != NULL); - } + // allocate memory for each row + g->edges = malloc(V * sizeof(int *)); + assert(g->edges != NULL); + // allocate memory for each column and initialise with 0 + for (i = 0; i < V; i++) + { + g->edges[i] = calloc(V, sizeof(int)); + assert(g->edges[i] != NULL); + } - return g; + return g; } // check if vertex is valid in a graph -bool validV(Graph g, Vertex v) { - return (g != NULL && v >= 0 && v < g->nV); +bool validV(Graph g, Vertex v) { return (g != NULL && v >= 0 && v < g->nV); } + +void insertEdge(Graph g, Edge e) +{ + assert(g != NULL && validV(g, e.v) && validV(g, e.w)); + + if (!g->edges[e.v][e.w]) + { // edge e not in graph + g->edges[e.v][e.w] = 1; + g->edges[e.w][e.v] = 1; + g->nE++; + } } -void insertEdge(Graph g, Edge e) { - assert(g != NULL && validV(g,e.v) && validV(g,e.w)); +void removeEdge(Graph g, Edge e) +{ + assert(g != NULL && validV(g, e.v) && validV(g, e.w)); - if (!g->edges[e.v][e.w]) { // edge e not in graph - g->edges[e.v][e.w] = 1; - g->edges[e.w][e.v] = 1; - g->nE++; - } + if (g->edges[e.v][e.w]) + { // edge e in graph + g->edges[e.v][e.w] = 0; + g->edges[e.w][e.v] = 0; + g->nE--; + } } -void removeEdge(Graph g, Edge e) { - assert(g != NULL && validV(g,e.v) && validV(g,e.w)); +bool adjacent(Graph g, Vertex v, Vertex w) +{ + assert(g != NULL && validV(g, v) && validV(g, w)); - if (g->edges[e.v][e.w]) { // edge e in graph - g->edges[e.v][e.w] = 0; - g->edges[e.w][e.v] = 0; - g->nE--; - } + return (g->edges[v][w] != 0); } -bool adjacent(Graph g, Vertex v, Vertex w) { - assert(g != NULL && validV(g,v) && validV(g,w)); - - return (g->edges[v][w] != 0); -} - -void showGraph(Graph g) { +void showGraph(Graph g) +{ assert(g != NULL); int i, j; printf("Number of vertices: %d\n", g->nV); printf("Number of edges: %d\n", g->nE); for (i = 0; i < g->nV; i++) - for (j = i+1; j < g->nV; j++) - if (g->edges[i][j]) - printf("Edge %d - %d\n", i, j); + for (j = i + 1; j < g->nV; j++) + if (g->edges[i][j]) + printf("Edge %d - %d\n", i, j); } -void freeGraph(Graph g) { - assert(g != NULL); +void freeGraph(Graph g) +{ + assert(g != NULL); - int i; - for (i = 0; i < g->nV; i++) - free(g->edges[i]); - free(g->edges); - free(g); + int i; + for (i = 0; i < g->nV; i++) + free(g->edges[i]); + free(g->edges); + free(g); } -// By -// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------. -// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. | -// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | | -// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | -// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | | -// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | | -// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | | -// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | | -// | | | || | | || | | || | | | | | | || | | | -// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' | -// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' - +// By +// .----------------. .----------------. .----------------. +// .-----------------. .----------------. .----------------. +// | .--------------. || .--------------. || .--------------. || +// .--------------. | | .--------------. || .--------------. | | | _________ | +// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ +// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \ +// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | | +// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | +// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || | +// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | | +// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ +// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.' +// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' +// | | | | | || | | || | | || | | | | | +// | || | | | | '--------------' || '--------------' || +// '--------------' || '--------------' | | '--------------' || '--------------' +// | +// '----------------' '----------------' '----------------' +// '----------------' '----------------' '----------------' + // Email : z5261243@unsw.edu.au // hhoanhtuann@gmail.com diff --git a/data_structures/graphs/Graph.h b/data_structures/graphs/Graph.h index 95a35e2a..23faea80 100644 --- a/data_structures/graphs/Graph.h +++ b/data_structures/graphs/Graph.h @@ -1,4 +1,4 @@ -// Graph ADT interface ... COMP2521 +// Graph ADT interface ... COMP2521 #include typedef struct GraphRep *Graph; @@ -7,31 +7,39 @@ typedef struct GraphRep *Graph; typedef int Vertex; // edges are pairs of vertices (end-points) -typedef struct Edge { - Vertex v; - Vertex w; +typedef struct Edge +{ + Vertex v; + Vertex w; } Edge; Graph newGraph(int); -void insertEdge(Graph, Edge); -void removeEdge(Graph, Edge); -bool adjacent(Graph, Vertex, Vertex); -void showGraph(Graph); -void freeGraph(Graph); +void insertEdge(Graph, Edge); +void removeEdge(Graph, Edge); +bool adjacent(Graph, Vertex, Vertex); +void showGraph(Graph); +void freeGraph(Graph); +// By +// .----------------. .----------------. .----------------. +// .-----------------. .----------------. .----------------. +// | .--------------. || .--------------. || .--------------. || +// .--------------. | | .--------------. || .--------------. | | | _________ | +// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ +// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \ +// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | | +// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | +// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || | +// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | | +// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ +// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.' +// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' +// | | | | | || | | || | | || | | | | | +// | || | | | | '--------------' || '--------------' || +// '--------------' || '--------------' | | '--------------' || '--------------' +// | +// '----------------' '----------------' '----------------' +// '----------------' '----------------' '----------------' -// By -// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------. -// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. | -// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | | -// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | -// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | | -// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | | -// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | | -// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | | -// | | | || | | || | | || | | | | | | || | | | -// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' | -// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' - // Email : z5261243@unsw.edu.au // hhoanhtuann@gmail.com diff --git a/data_structures/graphs/bfsQueue.c b/data_structures/graphs/bfsQueue.c index 8eb7b975..664c6dc5 100644 --- a/data_structures/graphs/bfsQueue.c +++ b/data_structures/graphs/bfsQueue.c @@ -1,81 +1,125 @@ -#include -#include -#include "queue.h" #include "Graph.h" +#include "queue.h" +#include +#include #define MAX_NODES 1000 -int visited[MAX_NODES]; // array to store visiting order - // indexed by vertex 0..nV-1 +int visited[MAX_NODES]; // array to store visiting order + // indexed by vertex 0..nV-1 -bool findPathBFS(Graph g, int nV, Vertex src, Vertex dest) { - Vertex v; - for (v = 0; v < nV; v++) - visited[v] = -1; +bool findPathBFS(Graph g, int nV, Vertex src, Vertex dest) +{ + Vertex v; + for (v = 0; v < nV; v++) + visited[v] = -1; - visited[src] = src; - queue Q = newQueue(); - QueueEnqueue(Q, src); - while (!QueueIsEmpty(Q)) { - v = QueueDequeue(Q); - Vertex w; - for (w = 0; w < nV; w++) - if (adjacent(g, v, w) && visited[w] == -1) { - visited[w] = v; - if (w == dest) - return true; - else - QueueEnqueue(Q, w); - } - } - return false; + visited[src] = src; + queue Q = newQueue(); + QueueEnqueue(Q, src); + while (!QueueIsEmpty(Q)) + { + v = QueueDequeue(Q); + Vertex w; + for (w = 0; w < nV; w++) + if (adjacent(g, v, w) && visited[w] == -1) + { + visited[w] = v; + if (w == dest) + return true; + else + QueueEnqueue(Q, w); + } + } + return false; } -int main(void) { - int V = 10; - Graph g = newGraph(V); +int main(void) +{ + int V = 10; + Graph g = newGraph(V); - Edge e; - e.v = 0; e.w = 1; insertEdge(g, e); - e.v = 0; e.w = 2; insertEdge(g, e); - e.v = 0; e.w = 5; insertEdge(g, e); - e.v = 1; e.w = 5; insertEdge(g, e); - e.v = 2; e.w = 3; insertEdge(g, e); - e.v = 3; e.w = 4; insertEdge(g, e); - e.v = 3; e.w = 5; insertEdge(g, e); - e.v = 3; e.w = 8; insertEdge(g, e); - e.v = 4; e.w = 5; insertEdge(g, e); - e.v = 4; e.w = 7; insertEdge(g, e); - e.v = 4; e.w = 8; insertEdge(g, e); - e.v = 5; e.w = 6; insertEdge(g, e); - e.v = 7; e.w = 8; insertEdge(g, e); - e.v = 7; e.w = 9; insertEdge(g, e); - e.v = 8; e.w = 9; insertEdge(g, e); + Edge e; + e.v = 0; + e.w = 1; + insertEdge(g, e); + e.v = 0; + e.w = 2; + insertEdge(g, e); + e.v = 0; + e.w = 5; + insertEdge(g, e); + e.v = 1; + e.w = 5; + insertEdge(g, e); + e.v = 2; + e.w = 3; + insertEdge(g, e); + e.v = 3; + e.w = 4; + insertEdge(g, e); + e.v = 3; + e.w = 5; + insertEdge(g, e); + e.v = 3; + e.w = 8; + insertEdge(g, e); + e.v = 4; + e.w = 5; + insertEdge(g, e); + e.v = 4; + e.w = 7; + insertEdge(g, e); + e.v = 4; + e.w = 8; + insertEdge(g, e); + e.v = 5; + e.w = 6; + insertEdge(g, e); + e.v = 7; + e.w = 8; + insertEdge(g, e); + e.v = 7; + e.w = 9; + insertEdge(g, e); + e.v = 8; + e.w = 9; + insertEdge(g, e); - int src = 0, dest = 6; - if (findPathBFS(g, V, src, dest)) { - Vertex v = dest; - while (v != src) { - printf("%d - ", v); - v = visited[v]; - } - printf("%d\n", src); - } - return 0; + int src = 0, dest = 6; + if (findPathBFS(g, V, src, dest)) + { + Vertex v = dest; + while (v != src) + { + printf("%d - ", v); + v = visited[v]; + } + printf("%d\n", src); + } + return 0; } -// By -// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------. -// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. | -// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | | -// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | -// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | | -// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | | -// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | | -// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | | -// | | | || | | || | | || | | | | | | || | | | -// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' | -// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' - +// By +// .----------------. .----------------. .----------------. +// .-----------------. .----------------. .----------------. +// | .--------------. || .--------------. || .--------------. || +// .--------------. | | .--------------. || .--------------. | | | _________ | +// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ +// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \ +// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | | +// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | +// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || | +// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | | +// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ +// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.' +// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' +// | | | | | || | | || | | || | | | | | +// | || | | | | '--------------' || '--------------' || +// '--------------' || '--------------' | | '--------------' || '--------------' +// | +// '----------------' '----------------' '----------------' +// '----------------' '----------------' '----------------' + // Email : z5261243@unsw.edu.au // hhoanhtuann@gmail.com diff --git a/data_structures/graphs/dfsRecursive.c b/data_structures/graphs/dfsRecursive.c index e9e960f8..689fc3d7 100644 --- a/data_structures/graphs/dfsRecursive.c +++ b/data_structures/graphs/dfsRecursive.c @@ -1,74 +1,104 @@ -#include -#include #include "Graph.h" +#include +#include #define MAX_NODES 1000 -int visited[MAX_NODES]; // array to store visiting order - // indexed by vertex 0..nV-1 +int visited[MAX_NODES]; // array to store visiting order + // indexed by vertex 0..nV-1 -bool dfsPathCheck(Graph g, int nV, Vertex v, Vertex dest) { - Vertex w; - for (w = 0; w < nV; w++) - if (adjacent(g, v, w) && visited[w] == -1) { - visited[w] = v; - if (w == dest) - return true; - else if (dfsPathCheck(g, nV, w, dest)) - return true; - } - return false; +bool dfsPathCheck(Graph g, int nV, Vertex v, Vertex dest) +{ + Vertex w; + for (w = 0; w < nV; w++) + if (adjacent(g, v, w) && visited[w] == -1) + { + visited[w] = v; + if (w == dest) + return true; + else if (dfsPathCheck(g, nV, w, dest)) + return true; + } + return false; } -bool findPathDFS(Graph g, int nV, Vertex src, Vertex dest) { - Vertex v; - for (v = 0; v < nV; v++) - visited[v] = -1; - visited[src] = src; - return dfsPathCheck(g, nV, src, dest); +bool findPathDFS(Graph g, int nV, Vertex src, Vertex dest) +{ + Vertex v; + for (v = 0; v < nV; v++) + visited[v] = -1; + visited[src] = src; + return dfsPathCheck(g, nV, src, dest); } -int main(void) { - int V = 6; - Graph g = newGraph(V); +int main(void) +{ + int V = 6; + Graph g = newGraph(V); - Edge e; - e.v = 0; e.w = 1; insertEdge(g, e); - e.v = 0; e.w = 4; insertEdge(g, e); - e.v = 0; e.w = 5; insertEdge(g, e); - e.v = 5; e.w = 4; insertEdge(g, e); - e.v = 4; e.w = 2; insertEdge(g, e); - e.v = 4; e.w = 3; insertEdge(g, e); - e.v = 5; e.w = 3; insertEdge(g, e); - e.v = 1; e.w = 2; insertEdge(g, e); - e.v = 3; e.w = 2; insertEdge(g, e); + Edge e; + e.v = 0; + e.w = 1; + insertEdge(g, e); + e.v = 0; + e.w = 4; + insertEdge(g, e); + e.v = 0; + e.w = 5; + insertEdge(g, e); + e.v = 5; + e.w = 4; + insertEdge(g, e); + e.v = 4; + e.w = 2; + insertEdge(g, e); + e.v = 4; + e.w = 3; + insertEdge(g, e); + e.v = 5; + e.w = 3; + insertEdge(g, e); + e.v = 1; + e.w = 2; + insertEdge(g, e); + e.v = 3; + e.w = 2; + insertEdge(g, e); - int src = 0, dest = 5; - if (findPathDFS(g, V, src, dest)) { - Vertex v = dest; - while (v != src) { - printf("%d - ", v); - v = visited[v]; - } - printf("%d\n", src); - } - return 0; + int src = 0, dest = 5; + if (findPathDFS(g, V, src, dest)) + { + Vertex v = dest; + while (v != src) + { + printf("%d - ", v); + v = visited[v]; + } + printf("%d\n", src); + } + return 0; } +// By +// .----------------. .----------------. .----------------. +// .-----------------. .----------------. .----------------. +// | .--------------. || .--------------. || .--------------. || +// .--------------. | | .--------------. || .--------------. | | | _________ | +// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ +// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \ +// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | | +// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | +// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || | +// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | | +// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ +// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.' +// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' +// | | | | | || | | || | | || | | | | | +// | || | | | | '--------------' || '--------------' || +// '--------------' || '--------------' | | '--------------' || '--------------' +// | +// '----------------' '----------------' '----------------' +// '----------------' '----------------' '----------------' -// By -// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------. -// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. | -// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | | -// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | -// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | | -// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | | -// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | | -// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | | -// | | | || | | || | | || | | | | | | || | | | -// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' | -// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' - // Email : z5261243@unsw.edu.au // hhoanhtuann@gmail.com - diff --git a/data_structures/graphs/euler.c b/data_structures/graphs/euler.c index 512abb0d..7cceeb39 100644 --- a/data_structures/graphs/euler.c +++ b/data_structures/graphs/euler.c @@ -1,82 +1,95 @@ -#include -#include #include "Graph.h" +#include +#include -// Return the number of vertices that v is +// Return the number of vertices that v is // connected to -int degree(Graph g, int nV, Vertex v) { - int deg = 0; - Vertex w; - for (w = 0; w < nV; w++) - if (adjacent(g, v, w)) - deg++; - return deg; +int degree(Graph g, int nV, Vertex v) +{ + int deg = 0; + Vertex w; + for (w = 0; w < nV; w++) + if (adjacent(g, v, w)) + deg++; + return deg; } -// If start from vertex v, decide if the +// If start from vertex v, decide if the // graph has euler path -bool hasEulerPath(Graph g, int nV, Vertex v, Vertex w) { - if (v != w) { - if (degree(g, nV, v) % 2 == 0 || degree(g, nV, w) % 2 == 0) - return false; - } else if (degree(g, nV, v) % 2 != 0) { - return false; - } - Vertex x; - for (x = 0; x < nV; x++) - if (x != v && x != w && degree(g, nV, x) % 2 != 0) - return false; - return true; +bool hasEulerPath(Graph g, int nV, Vertex v, Vertex w) +{ + if (v != w) + { + if (degree(g, nV, v) % 2 == 0 || degree(g, nV, w) % 2 == 0) + return false; + } + else if (degree(g, nV, v) % 2 != 0) + { + return false; + } + Vertex x; + for (x = 0; x < nV; x++) + if (x != v && x != w && degree(g, nV, x) % 2 != 0) + return false; + return true; } -int main(void) { - Edge e; - int n; +int main(void) +{ + Edge e; + int n; - printf("Enter the number of vertices: "); - scanf("%d", &n); - Graph g = newGraph(n); + printf("Enter the number of vertices: "); + scanf("%d", &n); + Graph g = newGraph(n); - Vertex src, dest; - printf("Enter source node: "); - scanf("%d", &src); - printf("Enter destination node: "); - scanf("%d", &dest); - - printf("Enter an edge (from): "); - while (scanf("%d", &e.v) == 1) { - printf("Enter an edge (to): "); - scanf("%d", &e.w); - insertEdge(g, e); - printf("Enter an edge (from): "); - } - printf("Finished.\n"); + Vertex src, dest; + printf("Enter source node: "); + scanf("%d", &src); + printf("Enter destination node: "); + scanf("%d", &dest); - printf("The graph has "); - if (hasEulerPath(g, n, src, dest)) - printf("an"); - else - printf("no"); - printf(" Euler path from %d to %d.\n", src, dest); + printf("Enter an edge (from): "); + while (scanf("%d", &e.v) == 1) + { + printf("Enter an edge (to): "); + scanf("%d", &e.w); + insertEdge(g, e); + printf("Enter an edge (from): "); + } + printf("Finished.\n"); - freeGraph(g); - return 0; + printf("The graph has "); + if (hasEulerPath(g, n, src, dest)) + printf("an"); + else + printf("no"); + printf(" Euler path from %d to %d.\n", src, dest); + + freeGraph(g); + return 0; } +// By +// .----------------. .----------------. .----------------. +// .-----------------. .----------------. .----------------. +// | .--------------. || .--------------. || .--------------. || +// .--------------. | | .--------------. || .--------------. | | | _________ | +// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ +// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \ +// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | | +// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | +// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || | +// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | | +// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ +// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.' +// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' +// | | | | | || | | || | | || | | | | | +// | || | | | | '--------------' || '--------------' || +// '--------------' || '--------------' | | '--------------' || '--------------' +// | +// '----------------' '----------------' '----------------' +// '----------------' '----------------' '----------------' - -// By -// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------. -// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. | -// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | | -// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | -// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | | -// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | | -// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | | -// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | | -// | | | || | | || | | || | | | | | | || | | | -// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' | -// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' - // Email : z5261243@unsw.edu.au // hhoanhtuann@gmail.com diff --git a/data_structures/graphs/hamiltonian.c b/data_structures/graphs/hamiltonian.c index ffe20700..ea3388cf 100644 --- a/data_structures/graphs/hamiltonian.c +++ b/data_structures/graphs/hamiltonian.c @@ -1,87 +1,104 @@ -#include -#include #include "Graph.h" +#include +#include #define MAX_NODES 1000 bool visited[MAX_NODES]; -bool hamiltonR(Graph g, int nV, Vertex v, Vertex dest, int d) { -// v = current vertex considered -// dest = destination vertex -// d = distance "remaining" until path found +bool hamiltonR(Graph g, int nV, Vertex v, Vertex dest, int d) +{ + // v = current vertex considered + // dest = destination vertex + // d = distance "remaining" until path found - Vertex w; - if (v == dest) { - return (d == 0); - } else { - visited[v] = true; - for (w = 0; w < nV; w++) { - if (adjacent(g, v, w) && !visited[w]) { - if (hamiltonR(g, nV, w, dest, d-1)) { - return true; - } - } - } - } - visited[v] = false; - return false; + Vertex w; + if (v == dest) + { + return (d == 0); + } + else + { + visited[v] = true; + for (w = 0; w < nV; w++) + { + if (adjacent(g, v, w) && !visited[w]) + { + if (hamiltonR(g, nV, w, dest, d - 1)) + { + return true; + } + } + } + } + visited[v] = false; + return false; } -bool hasHamiltonianPath(Graph g, int nV, Vertex src, Vertex dest) { - Vertex v; - for (v = 0; v < nV; v++) - visited[v] = false; - return hamiltonR(g, nV, src, dest, nV-1); +bool hasHamiltonianPath(Graph g, int nV, Vertex src, Vertex dest) +{ + Vertex v; + for (v = 0; v < nV; v++) + visited[v] = false; + return hamiltonR(g, nV, src, dest, nV - 1); } -int main(void) { - Edge e; - int n; +int main(void) +{ + Edge e; + int n; - printf("Enter the number of vertices: "); - scanf("%d", &n); - Graph g = newGraph(n); + printf("Enter the number of vertices: "); + scanf("%d", &n); + Graph g = newGraph(n); - Vertex src, dest; - printf("Enter source node: "); - scanf("%d", &src); - printf("Enter destination node: "); - scanf("%d", &dest); - - printf("Enter an edge (from): "); - while (scanf("%d", &e.v) == 1) { - printf("Enter an edge (to): "); - scanf("%d", &e.w); - insertEdge(g, e); - printf("Enter an edge (from): "); - } - printf("Finished.\n"); + Vertex src, dest; + printf("Enter source node: "); + scanf("%d", &src); + printf("Enter destination node: "); + scanf("%d", &dest); - printf("The graph has "); - if (hasHamiltonianPath(g, n, src, dest)) - printf("a"); - else - printf("no"); - printf(" Hamiltonian path from %d to %d.\n", src, dest); + printf("Enter an edge (from): "); + while (scanf("%d", &e.v) == 1) + { + printf("Enter an edge (to): "); + scanf("%d", &e.w); + insertEdge(g, e); + printf("Enter an edge (from): "); + } + printf("Finished.\n"); - freeGraph(g); - return 0; + printf("The graph has "); + if (hasHamiltonianPath(g, n, src, dest)) + printf("a"); + else + printf("no"); + printf(" Hamiltonian path from %d to %d.\n", src, dest); + + freeGraph(g); + return 0; } +// By +// .----------------. .----------------. .----------------. +// .-----------------. .----------------. .----------------. +// | .--------------. || .--------------. || .--------------. || +// .--------------. | | .--------------. || .--------------. | | | _________ | +// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ +// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \ +// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | | +// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | +// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || | +// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | | +// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ +// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.' +// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' +// | | | | | || | | || | | || | | | | | +// | || | | | | '--------------' || '--------------' || +// '--------------' || '--------------' | | '--------------' || '--------------' +// | +// '----------------' '----------------' '----------------' +// '----------------' '----------------' '----------------' -// By -// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------. -// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. | -// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | | -// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | -// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | | -// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | | -// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | | -// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | | -// | | | || | | || | | || | | | | | | || | | | -// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' | -// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' - // Email : z5261243@unsw.edu.au // hhoanhtuann@gmail.com diff --git a/data_structures/graphs/kruskal.c b/data_structures/graphs/kruskal.c index 4fd158a7..63a5163e 100644 --- a/data_structures/graphs/kruskal.c +++ b/data_structures/graphs/kruskal.c @@ -1,189 +1,187 @@ -// C program for Kruskal's algorithm to find Minimum Spanning Tree -// of a given connected, undirected and weighted graph -#include -#include -#include +// C program for Kruskal's algorithm to find Minimum Spanning Tree +// of a given connected, undirected and weighted graph +#include +#include +#include -// a structure to represent a weighted edge in graph -struct Edge -{ - int src, dest, weight; -}; +// a structure to represent a weighted edge in graph +struct Edge +{ + int src, dest, weight; +}; -// a structure to represent a connected, undirected -// and weighted graph -struct Graph -{ - // V-> Number of vertices, E-> Number of edges - int V, E; +// a structure to represent a connected, undirected +// and weighted graph +struct Graph +{ + // V-> Number of vertices, E-> Number of edges + int V, E; - // graph is represented as an array of edges. - // Since the graph is undirected, the edge - // from src to dest is also edge from dest - // to src. Both are counted as 1 edge here. - struct Edge* edge; -}; + // graph is represented as an array of edges. + // Since the graph is undirected, the edge + // from src to dest is also edge from dest + // to src. Both are counted as 1 edge here. + struct Edge *edge; +}; -// Creates a graph with V vertices and E edges -struct Graph* createGraph(int V, int E) -{ - struct Graph* graph = new Graph(); - graph->V = V; - graph->E = E; +// Creates a graph with V vertices and E edges +struct Graph *createGraph(int V, int E) +{ + struct Graph *graph = new Graph(); + graph->V = V; + graph->E = E; - graph->edge = new Edge[E]; + graph->edge = new Edge[E]; - return graph; -} + return graph; +} -// A structure to represent a subset for union-find -struct subset -{ - int parent; - int rank; -}; +// A structure to represent a subset for union-find +struct subset +{ + int parent; + int rank; +}; -// A utility function to find set of an element i -// (uses path compression technique) -int find(struct subset subsets[], int i) -{ - // find root and make root as parent of i - // (path compression) - if (subsets[i].parent != i) - subsets[i].parent = find(subsets, subsets[i].parent); +// A utility function to find set of an element i +// (uses path compression technique) +int find(struct subset subsets[], int i) +{ + // find root and make root as parent of i + // (path compression) + if (subsets[i].parent != i) + subsets[i].parent = find(subsets, subsets[i].parent); - return subsets[i].parent; -} + return subsets[i].parent; +} -// A function that does union of two sets of x and y -// (uses union by rank) -void Union(struct subset subsets[], int x, int y) -{ - int xroot = find(subsets, x); - int yroot = find(subsets, y); +// A function that does union of two sets of x and y +// (uses union by rank) +void Union(struct subset subsets[], int x, int y) +{ + int xroot = find(subsets, x); + int yroot = find(subsets, y); - // Attach smaller rank tree under root of high - // rank tree (Union by Rank) - if (subsets[xroot].rank < subsets[yroot].rank) - subsets[xroot].parent = yroot; - else if (subsets[xroot].rank > subsets[yroot].rank) - subsets[yroot].parent = xroot; + // Attach smaller rank tree under root of high + // rank tree (Union by Rank) + if (subsets[xroot].rank < subsets[yroot].rank) + subsets[xroot].parent = yroot; + else if (subsets[xroot].rank > subsets[yroot].rank) + subsets[yroot].parent = xroot; - // If ranks are same, then make one as root and - // increment its rank by one - else - { - subsets[yroot].parent = xroot; - subsets[xroot].rank++; - } -} + // If ranks are same, then make one as root and + // increment its rank by one + else + { + subsets[yroot].parent = xroot; + subsets[xroot].rank++; + } +} -// Compare two edges according to their weights. -// Used in qsort() for sorting an array of edges -int myComp(const void* a, const void* b) -{ - struct Edge* a1 = (struct Edge*)a; - struct Edge* b1 = (struct Edge*)b; - return a1->weight > b1->weight; -} +// Compare two edges according to their weights. +// Used in qsort() for sorting an array of edges +int myComp(const void *a, const void *b) +{ + struct Edge *a1 = (struct Edge *)a; + struct Edge *b1 = (struct Edge *)b; + return a1->weight > b1->weight; +} -// The main function to construct MST using Kruskal's algorithm -void KruskalMST(struct Graph* graph) -{ - int V = graph->V; - struct Edge result[V]; // Tnis will store the resultant MST - int e = 0; // An index variable, used for result[] - int i = 0; // An index variable, used for sorted edges +// The main function to construct MST using Kruskal's algorithm +void KruskalMST(struct Graph *graph) +{ + int V = graph->V; + struct Edge result[V]; // Tnis will store the resultant MST + int e = 0; // An index variable, used for result[] + int i = 0; // An index variable, used for sorted edges - // Step 1: Sort all the edges in non-decreasing - // order of their weight. If we are not allowed to - // change the given graph, we can create a copy of - // array of edges - qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp); + // Step 1: Sort all the edges in non-decreasing + // order of their weight. If we are not allowed to + // change the given graph, we can create a copy of + // array of edges + qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp); - // Allocate memory for creating V ssubsets - struct subset *subsets = - (struct subset*) malloc( V * sizeof(struct subset) ); + // Allocate memory for creating V ssubsets + struct subset *subsets = (struct subset *)malloc(V * sizeof(struct subset)); - // Create V subsets with single elements - for (int v = 0; v < V; ++v) - { - subsets[v].parent = v; - subsets[v].rank = 0; - } + // Create V subsets with single elements + for (int v = 0; v < V; ++v) + { + subsets[v].parent = v; + subsets[v].rank = 0; + } - // Number of edges to be taken is equal to V-1 - while (e < V - 1 && i < graph->E) - { - // Step 2: Pick the smallest edge. And increment - // the index for next iteration - struct Edge next_edge = graph->edge[i++]; + // Number of edges to be taken is equal to V-1 + while (e < V - 1 && i < graph->E) + { + // Step 2: Pick the smallest edge. And increment + // the index for next iteration + struct Edge next_edge = graph->edge[i++]; - int x = find(subsets, next_edge.src); - int y = find(subsets, next_edge.dest); + int x = find(subsets, next_edge.src); + int y = find(subsets, next_edge.dest); - // If including this edge does't cause cycle, - // include it in result and increment the index - // of result for next edge - if (x != y) - { - result[e++] = next_edge; - Union(subsets, x, y); - } - // Else discard the next_edge - } + // If including this edge does't cause cycle, + // include it in result and increment the index + // of result for next edge + if (x != y) + { + result[e++] = next_edge; + Union(subsets, x, y); + } + // Else discard the next_edge + } - // print the contents of result[] to display the - // built MST - printf("Following are the edges in the constructed MST\n"); - for (i = 0; i < e; ++i) - printf("%d -- %d == %d\n", result[i].src, result[i].dest, - result[i].weight); - return; -} + // print the contents of result[] to display the + // built MST + printf("Following are the edges in the constructed MST\n"); + for (i = 0; i < e; ++i) + printf("%d -- %d == %d\n", result[i].src, result[i].dest, + result[i].weight); + return; +} -// Driver program to test above functions -int main() -{ - /* Let us create following weighted graph - 10 - 0--------1 - | \ | - 6| 5\ |15 - | \ | - 2--------3 - 4 */ - int V = 4; // Number of vertices in graph - int E = 5; // Number of edges in graph - struct Graph* graph = createGraph(V, E); +// Driver program to test above functions +int main() +{ + /* Let us create following weighted graph + 10 + 0--------1 + | \ | + 6| 5\ |15 + | \ | + 2--------3 + 4 */ + int V = 4; // Number of vertices in graph + int E = 5; // Number of edges in graph + struct Graph *graph = createGraph(V, E); + // add edge 0-1 + graph->edge[0].src = 0; + graph->edge[0].dest = 1; + graph->edge[0].weight = 10; - // add edge 0-1 - graph->edge[0].src = 0; - graph->edge[0].dest = 1; - graph->edge[0].weight = 10; + // add edge 0-2 + graph->edge[1].src = 0; + graph->edge[1].dest = 2; + graph->edge[1].weight = 6; - // add edge 0-2 - graph->edge[1].src = 0; - graph->edge[1].dest = 2; - graph->edge[1].weight = 6; + // add edge 0-3 + graph->edge[2].src = 0; + graph->edge[2].dest = 3; + graph->edge[2].weight = 5; - // add edge 0-3 - graph->edge[2].src = 0; - graph->edge[2].dest = 3; - graph->edge[2].weight = 5; + // add edge 1-3 + graph->edge[3].src = 1; + graph->edge[3].dest = 3; + graph->edge[3].weight = 15; - // add edge 1-3 - graph->edge[3].src = 1; - graph->edge[3].dest = 3; - graph->edge[3].weight = 15; + // add edge 2-3 + graph->edge[4].src = 2; + graph->edge[4].dest = 3; + graph->edge[4].weight = 4; - // add edge 2-3 - graph->edge[4].src = 2; - graph->edge[4].dest = 3; - graph->edge[4].weight = 4; + KruskalMST(graph); - KruskalMST(graph); - - return 0; -} + return 0; +} diff --git a/data_structures/graphs/queue.c b/data_structures/graphs/queue.c index 8986d5d1..89ad6178 100644 --- a/data_structures/graphs/queue.c +++ b/data_structures/graphs/queue.c @@ -1,88 +1,104 @@ -// Queue ADT implementation ... COMP2521 +// Queue ADT implementation ... COMP2521 -#include -#include #include "queue.h" +#include +#include -typedef struct node { - int data; - struct node *next; +typedef struct node +{ + int data; + struct node *next; } NodeT; -typedef struct QueueRep { - int length; - NodeT *head; - NodeT *tail; +typedef struct QueueRep +{ + int length; + NodeT *head; + NodeT *tail; } QueueRep; // set up empty queue -queue newQueue() { - queue Q = malloc(sizeof(QueueRep)); - Q->length = 0; - Q->head = NULL; - Q->tail = NULL; - return Q; +queue newQueue() +{ + queue Q = malloc(sizeof(QueueRep)); + Q->length = 0; + Q->head = NULL; + Q->tail = NULL; + return Q; } // remove unwanted queue -void dropQueue(queue Q) { - NodeT *curr = Q->head; - while (curr != NULL) { - NodeT *temp = curr->next; - free(curr); - curr = temp; - } - free(Q); +void dropQueue(queue Q) +{ + NodeT *curr = Q->head; + while (curr != NULL) + { + NodeT *temp = curr->next; + free(curr); + curr = temp; + } + free(Q); } // check whether queue is empty -int QueueIsEmpty(queue Q) { - return (Q->length == 0); -} +int QueueIsEmpty(queue Q) { return (Q->length == 0); } // insert an int at end of queue -void QueueEnqueue(queue Q, int v) { - NodeT *new = malloc(sizeof(NodeT)); - assert(new != NULL); - new->data = v; - new->next = NULL; - if (Q->tail != NULL) { - Q->tail->next = new; - Q->tail = new; - } else { - Q->head = new; - Q->tail = new; - } - Q->length++; +void QueueEnqueue(queue Q, int v) +{ + NodeT *new = malloc(sizeof(NodeT)); + assert(new != NULL); + new->data = v; + new->next = NULL; + if (Q->tail != NULL) + { + Q->tail->next = new; + Q->tail = new; + } + else + { + Q->head = new; + Q->tail = new; + } + Q->length++; } // remove int from front of queue -int QueueDequeue(queue Q) { - assert(Q->length > 0); - NodeT *p = Q->head; - Q->head = Q->head->next; - if (Q->head == NULL) { - Q->tail = NULL; - } - Q->length--; - int d = p->data; - free(p); - return d; +int QueueDequeue(queue Q) +{ + assert(Q->length > 0); + NodeT *p = Q->head; + Q->head = Q->head->next; + if (Q->head == NULL) + { + Q->tail = NULL; + } + Q->length--; + int d = p->data; + free(p); + return d; } +// By +// .----------------. .----------------. .----------------. +// .-----------------. .----------------. .----------------. +// | .--------------. || .--------------. || .--------------. || +// .--------------. | | .--------------. || .--------------. | | | _________ | +// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ +// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \ +// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | | +// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | +// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || | +// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | | +// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ +// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.' +// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' +// | | | | | || | | || | | || | | | | | +// | || | | | | '--------------' || '--------------' || +// '--------------' || '--------------' | | '--------------' || '--------------' +// | +// '----------------' '----------------' '----------------' +// '----------------' '----------------' '----------------' -// By -// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------. -// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. | -// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | | -// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | -// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | | -// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | | -// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | | -// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | | -// | | | || | | || | | || | | | | | | || | | | -// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' | -// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' - // Email : z5261243@unsw.edu.au // hhoanhtuann@gmail.com diff --git a/data_structures/graphs/queue.h b/data_structures/graphs/queue.h index 57692c2f..a226b5dc 100644 --- a/data_structures/graphs/queue.h +++ b/data_structures/graphs/queue.h @@ -1,26 +1,33 @@ -// Queue ADT header file ... COMP2521 +// Queue ADT header file ... COMP2521 typedef struct QueueRep *queue; -queue newQueue(); // set up empty queue -void dropQueue(queue); // remove unwanted queue -int QueueIsEmpty(queue); // check whether queue is empty -void QueueEnqueue(queue, int); // insert an int at end of queue -int QueueDequeue(queue); // remove int from front of queue +queue newQueue(); // set up empty queue +void dropQueue(queue); // remove unwanted queue +int QueueIsEmpty(queue); // check whether queue is empty +void QueueEnqueue(queue, int); // insert an int at end of queue +int QueueDequeue(queue); // remove int from front of queue +// By +// .----------------. .----------------. .----------------. +// .-----------------. .----------------. .----------------. +// | .--------------. || .--------------. || .--------------. || +// .--------------. | | .--------------. || .--------------. | | | _________ | +// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ +// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \ +// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | | +// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | +// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || | +// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | | +// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ +// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.' +// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' +// | | | | | || | | || | | || | | | | | +// | || | | | | '--------------' || '--------------' || +// '--------------' || '--------------' | | '--------------' || '--------------' +// | +// '----------------' '----------------' '----------------' +// '----------------' '----------------' '----------------' -// By -// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------. -// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. | -// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | | -// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | -// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | | -// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | | -// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | | -// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | | -// | | | || | | || | | || | | | | | | || | | | -// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' | -// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' - // Email : z5261243@unsw.edu.au // hhoanhtuann@gmail.com diff --git a/data_structures/graphs/strongly_connected_components.c b/data_structures/graphs/strongly_connected_components.c index 1982540e..aed10aa1 100644 --- a/data_structures/graphs/strongly_connected_components.c +++ b/data_structures/graphs/strongly_connected_components.c @@ -1,59 +1,61 @@ #include #include -#define MAX_SIZE 40//Assume 40 nodes at max in graph -#define INT_MIN 0 -//A vertex of the graph +#define MAX_SIZE 40 // Assume 40 nodes at max in graph +#define INT_MIN 0 +// A vertex of the graph struct node { int vertex; - struct node* next; + struct node *next; }; -//Some declarations -struct node* createNode(int v); +// Some declarations +struct node *createNode(int v); struct Graph { int numVertices; - int* visited; - struct node** adjLists; // we need int** to store a two dimensional array. Similary, we need struct node** to store an array of Linked lists + int *visited; + struct node * + *adjLists; // we need int** to store a two dimensional array. Similary, + // we need struct node** to store an array of Linked lists }; -//Structure to create a stack, necessary for topological sorting +// Structure to create a stack, necessary for topological sorting struct Stack { - int arr[MAX_SIZE]; - int top; + int arr[MAX_SIZE]; + int top; }; -struct Graph* createGraph(int); -void addEdge(struct Graph*, int, int); -void printGraph(struct Graph*); -struct Graph* transpose(struct Graph*); -void fillOrder(int,struct Graph*, struct Stack*); -void scc(struct Graph*); -void dfs(struct Graph*, int); -struct Stack* createStack(); -void push(struct Stack*, int); -int pop(struct Stack*); +struct Graph *createGraph(int); +void addEdge(struct Graph *, int, int); +void printGraph(struct Graph *); +struct Graph *transpose(struct Graph *); +void fillOrder(int, struct Graph *, struct Stack *); +void scc(struct Graph *); +void dfs(struct Graph *, int); +struct Stack *createStack(); +void push(struct Stack *, int); +int pop(struct Stack *); int main() -{ - int vertices,edges,i,src,dst; - printf("Enter the number of vertices\n"); - scanf("%d",&vertices); - struct Graph* graph = createGraph(vertices); - printf("Enter the number of edges\n"); - scanf("%d",&edges); - for(i=0; ivisited[vertex]=1; - struct node* adjList = graph->adjLists[vertex]; - struct node* temp = adjList; - //First add all dependents (that is, children) to stack - while(temp!=NULL) { - int connectedVertex = temp->vertex; - if(graph->visited[connectedVertex] == 0) { - fillOrder(connectedVertex, graph, stack); - } - temp=temp->next; - } - //and then add itself - push(stack,vertex); -} -//Transpose the adjacency list -struct Graph* transpose(struct Graph* g) -{ - struct Graph* graph = createGraph(g->numVertices);//Number of vertices is same - int i=0; - for(i=0;inumVertices;i++) - { - struct node* temp=g->adjLists[i]; - while(temp!=NULL) - { - addEdge(graph,temp->vertex,i);//Reverse all edges - temp=temp->next; - } - } - return graph; -} -//Recursive dfs aproach -void dfs(struct Graph* graph, int vertex) { - struct node* adjList = graph->adjLists[vertex]; - struct node* temp = adjList; - - //Add vertex to visited list and print it graph->visited[vertex] = 1; - printf("%d ", vertex); - - //Recursively call the dfs function on all unvisited neighbours - while(temp!=NULL) { + struct node *adjList = graph->adjLists[vertex]; + struct node *temp = adjList; + // First add all dependents (that is, children) to stack + while (temp != NULL) + { int connectedVertex = temp->vertex; - if(graph->visited[connectedVertex] == 0) { - dfs(graph, connectedVertex); + if (graph->visited[connectedVertex] == 0) + { + fillOrder(connectedVertex, graph, stack); } temp = temp->next; - } + } + // and then add itself + push(stack, vertex); +} +// Transpose the adjacency list +struct Graph *transpose(struct Graph *g) +{ + struct Graph *graph = + createGraph(g->numVertices); // Number of vertices is same + int i = 0; + for (i = 0; i < g->numVertices; i++) + { + struct node *temp = g->adjLists[i]; + while (temp != NULL) + { + addEdge(graph, temp->vertex, i); // Reverse all edges + temp = temp->next; + } + } + return graph; +} +// Recursive dfs aproach +void dfs(struct Graph *graph, int vertex) +{ + struct node *adjList = graph->adjLists[vertex]; + struct node *temp = adjList; + + // Add vertex to visited list and print it + graph->visited[vertex] = 1; + printf("%d ", vertex); + + // Recursively call the dfs function on all unvisited neighbours + while (temp != NULL) + { + int connectedVertex = temp->vertex; + if (graph->visited[connectedVertex] == 0) + { + dfs(graph, connectedVertex); + } + temp = temp->next; + } } -//Strongly connected components -void scc(struct Graph* graph) +// Strongly connected components +void scc(struct Graph *graph) { - //Step I: Create a topological sort of the graph and store it in a stack - struct Stack* stack=createStack(); - int i=0; - for(i=0;inumVertices;i++) - { - //Execute topological sort on all elements - if(graph->visited[i]==0) - { - fillOrder(i,graph,stack); - } - } - //Step 2: Get the transpose graph - struct Graph* graphT=transpose(graph); - //Step 3: Perform a simple dfs by popping nodes from stack - while(stack->top!=-1) - { - int v=pop(stack); - if(graphT->visited[v]==0) - { - dfs(graphT,v); - printf("\n"); - } - } + // Step I: Create a topological sort of the graph and store it in a stack + struct Stack *stack = createStack(); + int i = 0; + for (i = 0; i < graph->numVertices; i++) + { + // Execute topological sort on all elements + if (graph->visited[i] == 0) + { + fillOrder(i, graph, stack); + } + } + // Step 2: Get the transpose graph + struct Graph *graphT = transpose(graph); + // Step 3: Perform a simple dfs by popping nodes from stack + while (stack->top != -1) + { + int v = pop(stack); + if (graphT->visited[v] == 0) + { + dfs(graphT, v); + printf("\n"); + } + } } - -//Allocate memory for a node -struct node* createNode(int v) + +// Allocate memory for a node +struct node *createNode(int v) { - struct node* newNode = malloc(sizeof(struct node)); + struct node *newNode = malloc(sizeof(struct node)); newNode->vertex = v; newNode->next = NULL; return newNode; } -//Allocate memory for the entire graph structure -struct Graph* createGraph(int vertices) +// Allocate memory for the entire graph structure +struct Graph *createGraph(int vertices) { - struct Graph* graph = malloc(sizeof(struct Graph)); + struct Graph *graph = malloc(sizeof(struct Graph)); graph->numVertices = vertices; - graph->adjLists = malloc(vertices * sizeof(struct node*)); + graph->adjLists = malloc(vertices * sizeof(struct node *)); graph->visited = malloc(vertices * sizeof(int)); - + int i; - for (i = 0; i < vertices; i++) { + for (i = 0; i < vertices; i++) + { graph->adjLists[i] = NULL; graph->visited[i] = 0; } return graph; } -//Creates a unidirectional graph -void addEdge(struct Graph* graph, int src, int dest) +// Creates a unidirectional graph +void addEdge(struct Graph *graph, int src, int dest) { // Add edge from src to dest - struct node* newNode = createNode(dest); + struct node *newNode = createNode(dest); newNode->next = graph->adjLists[src]; graph->adjLists[src] = newNode; } -//Utility function to see state of graph at a given time -void printGraph(struct Graph* graph) +// Utility function to see state of graph at a given time +void printGraph(struct Graph *graph) { int v; for (v = 0; v < graph->numVertices; v++) { - struct node* temp = graph->adjLists[v]; + struct node *temp = graph->adjLists[v]; printf("\n Adjacency list of vertex %d\n ", v); while (temp) { @@ -191,23 +200,24 @@ void printGraph(struct Graph* graph) printf("\n"); } } -//Creates a stack -struct Stack* createStack() +// Creates a stack +struct Stack *createStack() { - struct Stack* stack=malloc(sizeof(struct Stack)); - stack->top=-1; + struct Stack *stack = malloc(sizeof(struct Stack)); + stack->top = -1; return stack; } -//Pushes element into stack -void push(struct Stack* stack,int element) +// Pushes element into stack +void push(struct Stack *stack, int element) { - stack->arr[++stack->top]=element;//Increment then add, as we start from -1 + stack->arr[++stack->top] = + element; // Increment then add, as we start from -1 } -//Removes element from stack, or returns INT_MIN if stack empty -int pop(struct Stack* stack) +// Removes element from stack, or returns INT_MIN if stack empty +int pop(struct Stack *stack) { - if(stack->top==-1) - return INT_MIN; - else - return stack->arr[stack->top--]; + if (stack->top == -1) + return INT_MIN; + else + return stack->arr[stack->top--]; } diff --git a/data_structures/graphs/topologicalSort.c b/data_structures/graphs/topologicalSort.c index 4f3213da..ad008245 100644 --- a/data_structures/graphs/topologicalSort.c +++ b/data_structures/graphs/topologicalSort.c @@ -1,57 +1,59 @@ #include #include -#define MAX_SIZE 40//Assume 40 nodes at max in graph -#define INT_MIN 0 -//A vertex of the graph +#define MAX_SIZE 40 // Assume 40 nodes at max in graph +#define INT_MIN 0 +// A vertex of the graph struct node { int vertex; - struct node* next; + struct node *next; }; -//Some declarations -struct node* createNode(int v); +// Some declarations +struct node *createNode(int v); struct Graph { int numVertices; - int* visited; - struct node** adjLists; // we need int** to store a two dimensional array. Similary, we need struct node** to store an array of Linked lists + int *visited; + struct node * + *adjLists; // we need int** to store a two dimensional array. Similary, + // we need struct node** to store an array of Linked lists }; -//Structure to create a stack, necessary for topological sorting +// Structure to create a stack, necessary for topological sorting struct Stack { - int arr[MAX_SIZE]; - int top; + int arr[MAX_SIZE]; + int top; }; -struct Graph* createGraph(int); -void addEdge(struct Graph*, int, int); -void printGraph(struct Graph*); -void topologicalSortHelper(int,struct Graph*, struct Stack*); -void topologicalSort(struct Graph*); -struct Stack* createStack(); -void push(struct Stack*, int); -int pop(struct Stack*); +struct Graph *createGraph(int); +void addEdge(struct Graph *, int, int); +void printGraph(struct Graph *); +void topologicalSortHelper(int, struct Graph *, struct Stack *); +void topologicalSort(struct Graph *); +struct Stack *createStack(); +void push(struct Stack *, int); +int pop(struct Stack *); int main() -{ - int vertices,edges,i,src,dst; - printf("Enter the number of vertices\n"); - scanf("%d",&vertices); - struct Graph* graph = createGraph(vertices); - printf("Enter the number of edges\n"); - scanf("%d",&edges); - for(i=0; ivisited[vertex]=1; - struct node* adjList = graph->adjLists[vertex]; - struct node* temp = adjList; - //First add all dependents (that is, children) to stack - while(temp!=NULL) { + graph->visited[vertex] = 1; + struct node *adjList = graph->adjLists[vertex]; + struct node *temp = adjList; + // First add all dependents (that is, children) to stack + while (temp != NULL) + { int connectedVertex = temp->vertex; - if(graph->visited[connectedVertex] == 0) { - topologicalSortHelper(connectedVertex, graph, stack); - } - temp=temp->next; + if (graph->visited[connectedVertex] == 0) + { + topologicalSortHelper(connectedVertex, graph, stack); + } + temp = temp->next; } - //and then add itself - push(stack,vertex); + // and then add itself + push(stack, vertex); } -//Recursive topologial sort approach -void topologicalSort(struct Graph* graph) +// Recursive topologial sort approach +void topologicalSort(struct Graph *graph) { - struct Stack* stack=createStack(); - int i=0; - for(i=0;inumVertices;i++) - { - //Execute topological sort on all elements - if(graph->visited[i]==0) - { - topologicalSortHelper(i,graph,stack); - } - } - while(stack->top!=-1) - printf("%d ",pop(stack)); + struct Stack *stack = createStack(); + int i = 0; + for (i = 0; i < graph->numVertices; i++) + { + // Execute topological sort on all elements + if (graph->visited[i] == 0) + { + topologicalSortHelper(i, graph, stack); + } + } + while (stack->top != -1) + printf("%d ", pop(stack)); } -//Allocate memory for a node -struct node* createNode(int v) +// Allocate memory for a node +struct node *createNode(int v) { - struct node* newNode = malloc(sizeof(struct node)); + struct node *newNode = malloc(sizeof(struct node)); newNode->vertex = v; newNode->next = NULL; return newNode; } -//Allocate memory for the entire graph structure -struct Graph* createGraph(int vertices) +// Allocate memory for the entire graph structure +struct Graph *createGraph(int vertices) { - struct Graph* graph = malloc(sizeof(struct Graph)); + struct Graph *graph = malloc(sizeof(struct Graph)); graph->numVertices = vertices; - graph->adjLists = malloc(vertices * sizeof(struct node*)); + graph->adjLists = malloc(vertices * sizeof(struct node *)); graph->visited = malloc(vertices * sizeof(int)); - + int i; - for (i = 0; i < vertices; i++) { + for (i = 0; i < vertices; i++) + { graph->adjLists[i] = NULL; graph->visited[i] = 0; } return graph; } -//Creates a unidirectional graph -void addEdge(struct Graph* graph, int src, int dest) +// Creates a unidirectional graph +void addEdge(struct Graph *graph, int src, int dest) { // Add edge from src to dest - struct node* newNode = createNode(dest); + struct node *newNode = createNode(dest); newNode->next = graph->adjLists[src]; graph->adjLists[src] = newNode; } -//Utility function to see state of graph at a given time -void printGraph(struct Graph* graph) +// Utility function to see state of graph at a given time +void printGraph(struct Graph *graph) { int v; for (v = 0; v < graph->numVertices; v++) { - struct node* temp = graph->adjLists[v]; + struct node *temp = graph->adjLists[v]; printf("\n Adjacency list of vertex %d\n ", v); while (temp) { @@ -143,24 +148,24 @@ void printGraph(struct Graph* graph) printf("\n"); } } -//Creates a stack -struct Stack* createStack() +// Creates a stack +struct Stack *createStack() { - struct Stack* stack=malloc(sizeof(struct Stack)); - stack->top=-1; + struct Stack *stack = malloc(sizeof(struct Stack)); + stack->top = -1; return stack; } -//Pushes element into stack -void push(struct Stack* stack,int element) +// Pushes element into stack +void push(struct Stack *stack, int element) { - stack->arr[++stack->top]=element;//Increment then add, as we start from -1 + stack->arr[++stack->top] = + element; // Increment then add, as we start from -1 } -//Removes element from stack, or returns INT_MIN if stack empty -int pop(struct Stack* stack) +// Removes element from stack, or returns INT_MIN if stack empty +int pop(struct Stack *stack) { - if(stack->top==-1) - return INT_MIN; - else - return stack->arr[stack->top--]; + if (stack->top == -1) + return INT_MIN; + else + return stack->arr[stack->top--]; } - diff --git a/data_structures/graphs/transitiveClosure.c b/data_structures/graphs/transitiveClosure.c index d5936fe4..86831512 100644 --- a/data_structures/graphs/transitiveClosure.c +++ b/data_structures/graphs/transitiveClosure.c @@ -1,48 +1,61 @@ -#include #include +#include #define NODES 4 -int digraph[NODES][NODES]={ {0,1,1,1}, {1,0,1,0}, {0,1,0,0}, {0,0,0,0} }; +int digraph[NODES][NODES] = { + {0, 1, 1, 1}, {1, 0, 1, 0}, {0, 1, 0, 0}, {0, 0, 0, 0}}; int tc[NODES][NODES]; -void warshall() { - int i, s, t; - for (s = 0; s < NODES; s++) - for (t = 0; t < NODES; t++) - tc[s][t] = digraph[s][t]; +void warshall() +{ + int i, s, t; + for (s = 0; s < NODES; s++) + for (t = 0; t < NODES; t++) + tc[s][t] = digraph[s][t]; - for (i = 0; i < NODES; i++) - for (s = 0; s < NODES; s++) - for (t = 0; t < NODES; t++) - if (tc[s][i] && tc[i][t]) - tc[s][t] = 1; + for (i = 0; i < NODES; i++) + for (s = 0; s < NODES; s++) + for (t = 0; t < NODES; t++) + if (tc[s][i] && tc[i][t]) + tc[s][t] = 1; } -int main(void) { - warshall(); - int i, j; - for (i = 0; i < NODES; i++) { - for (j = 0; j < NODES; j++) { - printf("%d ", tc[i][j]); - } - putchar('\n'); - } - return 0; +int main(void) +{ + warshall(); + int i, j; + for (i = 0; i < NODES; i++) + { + for (j = 0; j < NODES; j++) + { + printf("%d ", tc[i][j]); + } + putchar('\n'); + } + return 0; } -// By -// .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------. -// | .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. | -// | | _________ | || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ | || | ____ | | -// | | | _ _ | | || ||_ _||_ _|| || | / \ | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | -// | | |_/ | | \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | |__| | | || | / .--. \ | | -// | | | | | || | | ' ' | | || | / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | | -// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ | | | | _| | | |_ | || | \ `--' / | | -// | | |_____| | || | `.__.' | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' | | -// | | | || | | || | | || | | | | | | || | | | -// | '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' | -// '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' - +// By +// .----------------. .----------------. .----------------. +// .-----------------. .----------------. .----------------. +// | .--------------. || .--------------. || .--------------. || +// .--------------. | | .--------------. || .--------------. | | | _________ | +// || | _____ _____ | || | __ | || | ____ _____ | | | | ____ ____ +// | || | ____ | | | | | _ _ | | || ||_ _||_ _|| || | / \ +// | || ||_ \|_ _| | | | | |_ || _| | || | .' `. | | | | |_/ | | +// \_| | || | | | | | | || | / /\ \ | || | | \ | | | | | | | +// |__| | | || | / .--. \ | | | | | | | || | | ' ' | | || | +// / ____ \ | || | | |\ \| | | | | | | __ | | || | | | | | | | +// | | _| |_ | || | \ `--' / | || | _/ / \ \_ | || | _| |_\ |_ +// | | | | _| | | |_ | || | \ `--' / | | | | |_____| | || | `.__.' +// | || ||____| |____|| || ||_____|\____| | | | | |____||____| | || | `.____.' +// | | | | | || | | || | | || | | | | | +// | || | | | | '--------------' || '--------------' || +// '--------------' || '--------------' | | '--------------' || '--------------' +// | +// '----------------' '----------------' '----------------' +// '----------------' '----------------' '----------------' + // Email : z5261243@unsw.edu.au // hhoanhtuann@gmail.com diff --git a/data_structures/hash_set/hash_set.c b/data_structures/hash_set/hash_set.c index 1d340e68..f7ea46b4 100644 --- a/data_structures/hash_set/hash_set.c +++ b/data_structures/hash_set/hash_set.c @@ -21,8 +21,10 @@ unsigned add(hash_set_t *set, void *value) unsigned put(hash_set_t *set, long long hash, void *value) { - if (contains_hash(set, hash)) { - if (set->keys[retrieve_index_from_hash(hash, set->capacity)] == value) { + if (contains_hash(set, hash)) + { + if (set->keys[retrieve_index_from_hash(hash, set->capacity)] == value) + { return 0; } @@ -40,7 +42,10 @@ unsigned put(hash_set_t *set, long long hash, void *value) int contains(hash_set_t *set, void *value) { - return set->keys[retrieve_index_from_hash(hash(value), set->capacity)] == value ? 1 : 0; + return set->keys[retrieve_index_from_hash(hash(value), set->capacity)] == + value + ? 1 + : 0; } int contains_hash(hash_set_t *set, long long hash) @@ -48,11 +53,11 @@ int contains_hash(hash_set_t *set, long long hash) return set->keys[retrieve_index_from_hash(hash, set->capacity)] ? 1 : 0; } -void delete(hash_set_t *set, void *value) { +void delete (hash_set_t *set, void *value) +{ set->keys[retrieve_index_from_hash(hash(value), set->capacity)] = NULL; } - // adler_32 hash long long hash(void *value) { @@ -62,7 +67,8 @@ long long hash(void *value) int b = 0; const int MODADLER = 65521; - for (int i = 0; str[i] != '\0'; i++) { + for (int i = 0; str[i] != '\0'; i++) + { a = (a + str[i]) % MODADLER; b = (b + a) % MODADLER; } @@ -79,14 +85,17 @@ void resize(hash_set_t *set) { void **keys_resized = calloc((set->capacity <<= 1), sizeof(void **)); - for (int i = 0; i < set->length; i++) { - keys_resized[retrieve_index_from_hash(hash(set->values[i]), set->capacity)] = set->values[i]; + for (int i = 0; i < set->length; i++) + { + keys_resized[retrieve_index_from_hash(hash(set->values[i]), + set->capacity)] = set->values[i]; } free(set->keys); set->keys = keys_resized; - void **new_values = (void **)realloc(set->values, set->capacity * sizeof(void **)); + void **new_values = + (void **)realloc(set->values, set->capacity * sizeof(void **)); set->values = new_values; } diff --git a/data_structures/hash_set/hash_set.h b/data_structures/hash_set/hash_set.h index cb79d24b..593c3251 100644 --- a/data_structures/hash_set/hash_set.h +++ b/data_structures/hash_set/hash_set.h @@ -3,7 +3,8 @@ #define DEFAULT_HASH_SET_CAPACITY 1 << 10 -typedef struct { +typedef struct +{ unsigned capacity; unsigned length; void **values; @@ -20,11 +21,12 @@ extern int contains(hash_set_t *set, void *value); int contains_hash(hash_set_t *set, long long hash); -extern void delete(hash_set_t *set, void *value); +extern void delete (hash_set_t *set, void *value); extern long long hash(void *value); -extern unsigned retrieve_index_from_hash(const long long hash, const unsigned capacity); +extern unsigned retrieve_index_from_hash(const long long hash, + const unsigned capacity); extern void resize(hash_set_t *set); diff --git a/data_structures/hash_set/main.c b/data_structures/hash_set/main.c index 6517aea7..badc1cf7 100644 --- a/data_structures/hash_set/main.c +++ b/data_structures/hash_set/main.c @@ -34,7 +34,7 @@ int main() printf("contains %d ? %d\n", v7, contains(set, &v7)); - delete(set, &v6); + delete (set, &v6); printf("contains %d ? %d\n", v6, contains(set, &v6)); diff --git a/data_structures/heap/max_heap.c b/data_structures/heap/max_heap.c index f529a7ac..eb40695f 100644 --- a/data_structures/heap/max_heap.c +++ b/data_structures/heap/max_heap.c @@ -1,122 +1,148 @@ -#include -#include +#include +#include -typedef struct max_heap{ - int *p; - int size; - int count; -}Heap; +typedef struct max_heap +{ + int *p; + int size; + int count; +} Heap; -Heap* create_heap(Heap* heap); /*Creates a max_heap structure and returns a pointer to the struct*/ -void down_heapify(Heap* heap, int index);/*Pushes an element downwards in the heap to find its correct position*/ -void up_heapify(Heap* heap, int index);/*Pushes an element upwards in the heap to find its correct position*/ -void push(Heap* heap, int x);/*Inserts an element in the heap*/ -void pop(Heap* heap);/*Removes the top element from the heap*/ -int top(Heap* heap);/*Returns the top element of the heap or returns INT_MIN if heap is empty*/ -int empty(Heap* heap);/*Checks if heap is empty*/ -int size(Heap* heap);/*Returns the size of heap*/ +Heap *create_heap(Heap *heap); /*Creates a max_heap structure and returns a + pointer to the struct*/ +void down_heapify(Heap *heap, int index); /*Pushes an element downwards in the + heap to find its correct position*/ +void up_heapify(Heap *heap, int index); /*Pushes an element upwards in the heap + to find its correct position*/ +void push(Heap *heap, int x); /*Inserts an element in the heap*/ +void pop(Heap *heap); /*Removes the top element from the heap*/ +int top(Heap *heap); /*Returns the top element of the heap or returns INT_MIN if + heap is empty*/ +int empty(Heap *heap); /*Checks if heap is empty*/ +int size(Heap *heap); /*Returns the size of heap*/ -int main(){ - Heap* head = create_heap(head); - push(head, 10); - printf("Pushing element : 10\n"); - push(head, 3); - printf("Pushing element : 3\n"); - push(head, 2); - printf("Pushing element : 2\n"); - push(head, 8); - printf("Pushing element : 8\n"); - printf("Top element = %d \n", top(head)); - push(head, 1); - printf("Pushing element : 1\n"); - push(head, 7); - printf("Pushing element : 7\n"); - printf("Top element = %d \n", top(head)); - pop(head); - printf("Popping an element.\n"); - printf("Top element = %d \n", top(head)); - pop(head); - printf("Popping an element.\n"); - printf("Top element = %d \n", top(head)); - printf("\n"); - return 0; +int main() +{ + Heap *head = create_heap(head); + push(head, 10); + printf("Pushing element : 10\n"); + push(head, 3); + printf("Pushing element : 3\n"); + push(head, 2); + printf("Pushing element : 2\n"); + push(head, 8); + printf("Pushing element : 8\n"); + printf("Top element = %d \n", top(head)); + push(head, 1); + printf("Pushing element : 1\n"); + push(head, 7); + printf("Pushing element : 7\n"); + printf("Top element = %d \n", top(head)); + pop(head); + printf("Popping an element.\n"); + printf("Top element = %d \n", top(head)); + pop(head); + printf("Popping an element.\n"); + printf("Top element = %d \n", top(head)); + printf("\n"); + return 0; } -Heap* create_heap(Heap* heap){ - heap = (Heap *)malloc(sizeof(Heap)); - heap->size = 1; - heap->p = (int *)malloc(heap->size*sizeof(int)); - heap->count = 0; - return heap; +Heap *create_heap(Heap *heap) +{ + heap = (Heap *)malloc(sizeof(Heap)); + heap->size = 1; + heap->p = (int *)malloc(heap->size * sizeof(int)); + heap->count = 0; + return heap; } -void down_heapify(Heap* heap, int index){ - if(index>=heap->count)return; - int left = index*2+1; - int right = index*2+2; - int leftflag = 0, rightflag = 0; - - int maximum = *((heap->p)+index); - if(leftcount && maximum<*((heap->p)+left)){ - maximum = *((heap->p)+left); - leftflag = 1; - } - if(rightcount && maximum<*((heap->p)+right)){ - maximum = *((heap->p)+right); - leftflag = 0; - rightflag = 1; - } - if(leftflag){ - *((heap->p)+left) = *((heap->p)+index); - *((heap->p)+index) = maximum; - down_heapify(heap, left); - } - if(rightflag){ - *((heap->p)+right) = *((heap->p)+index); - *((heap->p)+index) = maximum; - down_heapify(heap, right); - } +void down_heapify(Heap *heap, int index) +{ + if (index >= heap->count) + return; + int left = index * 2 + 1; + int right = index * 2 + 2; + int leftflag = 0, rightflag = 0; + + int maximum = *((heap->p) + index); + if (left < heap->count && maximum < *((heap->p) + left)) + { + maximum = *((heap->p) + left); + leftflag = 1; + } + if (right < heap->count && maximum < *((heap->p) + right)) + { + maximum = *((heap->p) + right); + leftflag = 0; + rightflag = 1; + } + if (leftflag) + { + *((heap->p) + left) = *((heap->p) + index); + *((heap->p) + index) = maximum; + down_heapify(heap, left); + } + if (rightflag) + { + *((heap->p) + right) = *((heap->p) + index); + *((heap->p) + index) = maximum; + down_heapify(heap, right); + } } -void up_heapify(Heap* heap, int index){ - int parent = (index-1)/2; - if(parent<0)return; - if(*((heap->p)+index)>*((heap->p)+parent)){ - int temp = *((heap->p)+index); - *((heap->p)+index) = *((heap->p)+parent); - *((heap->p)+parent) = temp; - up_heapify(heap, parent); - } +void up_heapify(Heap *heap, int index) +{ + int parent = (index - 1) / 2; + if (parent < 0) + return; + if (*((heap->p) + index) > *((heap->p) + parent)) + { + int temp = *((heap->p) + index); + *((heap->p) + index) = *((heap->p) + parent); + *((heap->p) + parent) = temp; + up_heapify(heap, parent); + } } -void push(Heap* heap, int x){ - if(heap->count>=heap->size)return; - *((heap->p)+heap->count) = x; - heap->count++; - if(4*heap->count >= 3*heap->size){ - heap->size *= 2; - (heap->p) = (int *)realloc((heap->p), (heap->size)*sizeof(int)); - } - up_heapify(heap, heap->count - 1); +void push(Heap *heap, int x) +{ + if (heap->count >= heap->size) + return; + *((heap->p) + heap->count) = x; + heap->count++; + if (4 * heap->count >= 3 * heap->size) + { + heap->size *= 2; + (heap->p) = (int *)realloc((heap->p), (heap->size) * sizeof(int)); + } + up_heapify(heap, heap->count - 1); } -void pop(Heap* heap){ - if(heap->count==0)return; - heap->count--; - int temp = *((heap->p)+heap->count); - *((heap->p)+heap->count) = *(heap->p); - *(heap->p) = temp; - down_heapify(heap, 0); - if(4*heap->count<=heap->size){ - heap->size /= 2; - (heap->p) = (int *)realloc((heap->p), (heap->size)*sizeof(int)); - } +void pop(Heap *heap) +{ + if (heap->count == 0) + return; + heap->count--; + int temp = *((heap->p) + heap->count); + *((heap->p) + heap->count) = *(heap->p); + *(heap->p) = temp; + down_heapify(heap, 0); + if (4 * heap->count <= heap->size) + { + heap->size /= 2; + (heap->p) = (int *)realloc((heap->p), (heap->size) * sizeof(int)); + } } -int top(Heap* heap){ - if(heap->count!=0)return *(heap->p); - else return INT_MIN; +int top(Heap *heap) +{ + if (heap->count != 0) + return *(heap->p); + else + return INT_MIN; } -int empty(Heap* heap){ - if(heap->count!=0)return 0; - else return 1; -} -int size(Heap* heap){ - return heap->count; +int empty(Heap *heap) +{ + if (heap->count != 0) + return 0; + else + return 1; } +int size(Heap *heap) { return heap->count; } diff --git a/data_structures/heap/min_heap.c b/data_structures/heap/min_heap.c index 066f9a11..88bfee1c 100644 --- a/data_structures/heap/min_heap.c +++ b/data_structures/heap/min_heap.c @@ -1,122 +1,148 @@ -#include -#include +#include +#include -typedef struct min_heap{ - int *p; - int size; - int count; -}Heap; +typedef struct min_heap +{ + int *p; + int size; + int count; +} Heap; -Heap* create_heap(Heap* heap); /*Creates a min_heap structure and returns a pointer to the struct*/ -void down_heapify(Heap* heap, int index);/*Pushes an element downwards in the heap to find its correct position*/ -void up_heapify(Heap* heap, int index);/*Pushes an element upwards in the heap to find its correct position*/ -void push(Heap* heap, int x);/*Inserts an element in the heap*/ -void pop(Heap* heap);/*Removes the top element from the heap*/ -int top(Heap* heap);/*Returns the top element of the heap or returns INT_MIN if heap is empty*/ -int empty(Heap* heap);/*Checks if heap is empty*/ -int size(Heap* heap);/*Returns the size of heap*/ +Heap *create_heap(Heap *heap); /*Creates a min_heap structure and returns a + pointer to the struct*/ +void down_heapify(Heap *heap, int index); /*Pushes an element downwards in the + heap to find its correct position*/ +void up_heapify(Heap *heap, int index); /*Pushes an element upwards in the heap + to find its correct position*/ +void push(Heap *heap, int x); /*Inserts an element in the heap*/ +void pop(Heap *heap); /*Removes the top element from the heap*/ +int top(Heap *heap); /*Returns the top element of the heap or returns INT_MIN if + heap is empty*/ +int empty(Heap *heap); /*Checks if heap is empty*/ +int size(Heap *heap); /*Returns the size of heap*/ -int main(){ - Heap* head = create_heap(head); - push(head, 10); - printf("Pushing element : 10\n"); - push(head, 3); - printf("Pushing element : 3\n"); - push(head, 2); - printf("Pushing element : 2\n"); - push(head, 8); - printf("Pushing element : 8\n"); - printf("Top element = %d \n", top(head)); - push(head, 1); - printf("Pushing element : 1\n"); - push(head, 7); - printf("Pushing element : 7\n"); - printf("Top element = %d \n", top(head)); - pop(head); - printf("Popping an element.\n"); - printf("Top element = %d \n", top(head)); - pop(head); - printf("Popping an element.\n"); - printf("Top element = %d \n", top(head)); - printf("\n"); - return 0; +int main() +{ + Heap *head = create_heap(head); + push(head, 10); + printf("Pushing element : 10\n"); + push(head, 3); + printf("Pushing element : 3\n"); + push(head, 2); + printf("Pushing element : 2\n"); + push(head, 8); + printf("Pushing element : 8\n"); + printf("Top element = %d \n", top(head)); + push(head, 1); + printf("Pushing element : 1\n"); + push(head, 7); + printf("Pushing element : 7\n"); + printf("Top element = %d \n", top(head)); + pop(head); + printf("Popping an element.\n"); + printf("Top element = %d \n", top(head)); + pop(head); + printf("Popping an element.\n"); + printf("Top element = %d \n", top(head)); + printf("\n"); + return 0; } -Heap* create_heap(Heap* heap){ - heap = (Heap *)malloc(sizeof(Heap)); - heap->size = 1; - heap->p = (int *)malloc(heap->size*sizeof(int)); - heap->count = 0; - return heap; +Heap *create_heap(Heap *heap) +{ + heap = (Heap *)malloc(sizeof(Heap)); + heap->size = 1; + heap->p = (int *)malloc(heap->size * sizeof(int)); + heap->count = 0; + return heap; } -void down_heapify(Heap* heap, int index){ - if(index>=heap->count)return; - int left = index*2+1; - int right = index*2+2; - int leftflag = 0, rightflag = 0; - - int minimum = *((heap->p)+index); - if(leftcount && minimum>*((heap->p)+left)){ - minimum = *((heap->p)+left); - leftflag = 1; - } - if(rightcount && minimum>*((heap->p)+right)){ - minimum = *((heap->p)+right); - leftflag = 0; - rightflag = 1; - } - if(leftflag){ - *((heap->p)+left) = *((heap->p)+index); - *((heap->p)+index) = minimum; - down_heapify(heap, left); - } - if(rightflag){ - *((heap->p)+right) = *((heap->p)+index); - *((heap->p)+index) = minimum; - down_heapify(heap, right); - } +void down_heapify(Heap *heap, int index) +{ + if (index >= heap->count) + return; + int left = index * 2 + 1; + int right = index * 2 + 2; + int leftflag = 0, rightflag = 0; + + int minimum = *((heap->p) + index); + if (left < heap->count && minimum > *((heap->p) + left)) + { + minimum = *((heap->p) + left); + leftflag = 1; + } + if (right < heap->count && minimum > *((heap->p) + right)) + { + minimum = *((heap->p) + right); + leftflag = 0; + rightflag = 1; + } + if (leftflag) + { + *((heap->p) + left) = *((heap->p) + index); + *((heap->p) + index) = minimum; + down_heapify(heap, left); + } + if (rightflag) + { + *((heap->p) + right) = *((heap->p) + index); + *((heap->p) + index) = minimum; + down_heapify(heap, right); + } } -void up_heapify(Heap* heap, int index){ - int parent = (index-1)/2; - if(parent<0)return; - if(*((heap->p)+index)<*((heap->p)+parent)){ - int temp = *((heap->p)+index); - *((heap->p)+index) = *((heap->p)+parent); - *((heap->p)+parent) = temp; - up_heapify(heap, parent); - } +void up_heapify(Heap *heap, int index) +{ + int parent = (index - 1) / 2; + if (parent < 0) + return; + if (*((heap->p) + index) < *((heap->p) + parent)) + { + int temp = *((heap->p) + index); + *((heap->p) + index) = *((heap->p) + parent); + *((heap->p) + parent) = temp; + up_heapify(heap, parent); + } } -void push(Heap* heap, int x){ - if(heap->count>=heap->size)return; - *((heap->p)+heap->count) = x; - heap->count++; - if(4*heap->count >= 3*heap->size){ - heap->size *= 2; - (heap->p) = (int *)realloc((heap->p), (heap->size)*sizeof(int)); - } - up_heapify(heap, heap->count - 1); +void push(Heap *heap, int x) +{ + if (heap->count >= heap->size) + return; + *((heap->p) + heap->count) = x; + heap->count++; + if (4 * heap->count >= 3 * heap->size) + { + heap->size *= 2; + (heap->p) = (int *)realloc((heap->p), (heap->size) * sizeof(int)); + } + up_heapify(heap, heap->count - 1); } -void pop(Heap* heap){ - if(heap->count==0)return; - heap->count--; - int temp = *((heap->p)+heap->count); - *((heap->p)+heap->count) = *(heap->p); - *(heap->p) = temp; - down_heapify(heap, 0); - if(4*heap->count<=heap->size){ - heap->size /= 2; - (heap->p) = (int *)realloc((heap->p), (heap->size)*sizeof(int)); - } +void pop(Heap *heap) +{ + if (heap->count == 0) + return; + heap->count--; + int temp = *((heap->p) + heap->count); + *((heap->p) + heap->count) = *(heap->p); + *(heap->p) = temp; + down_heapify(heap, 0); + if (4 * heap->count <= heap->size) + { + heap->size /= 2; + (heap->p) = (int *)realloc((heap->p), (heap->size) * sizeof(int)); + } } -int top(Heap* heap){ - if(heap->count!=0)return *(heap->p); - else return INT_MIN; +int top(Heap *heap) +{ + if (heap->count != 0) + return *(heap->p); + else + return INT_MIN; } -int empty(Heap* heap){ - if(heap->count!=0)return 0; - else return 1; -} -int size(Heap* heap){ - return heap->count; +int empty(Heap *heap) +{ + if (heap->count != 0) + return 0; + else + return 1; } +int size(Heap *heap) { return heap->count; } diff --git a/data_structures/linked_list/ascendingpriorityqueue.c b/data_structures/linked_list/ascendingpriorityqueue.c index fdce503b..e252dc58 100644 --- a/data_structures/linked_list/ascendingpriorityqueue.c +++ b/data_structures/linked_list/ascendingpriorityqueue.c @@ -1,185 +1,182 @@ -/* Ascending priority queue using Linked List - Program to implement Ascending priority queue using Linked List */ +/* Ascending priority queue using Linked List - Program to implement Ascending + * priority queue using Linked List */ -/*A priority queue is a special type of queue in which each element is associated with a priority and is served according -to its priority. If elements with the same priority occur, they are served according to their order in the queue. +/*A priority queue is a special type of queue in which each element is +associated with a priority and is served according to its priority. If elements +with the same priority occur, they are served according to their order in the +queue. -Generally, the value of the element itself is considered for assigning the priority. +Generally, the value of the element itself is considered for assigning the +priority. -For example: The element with the highest value is considered as the highest priority element. However, in other cases, -we can assume the element with the lowest value as the highest priority element. In other cases, -we can set priorities according to our needs. +For example: The element with the highest value is considered as the highest +priority element. However, in other cases, we can assume the element with the +lowest value as the highest priority element. In other cases, we can set +priorities according to our needs. -In a queue, the first-in-first-out rule is implemented whereas, in a priority queue, the values are removed on the basis of priority. -The element with the highest priority is removed first. +In a queue, the first-in-first-out rule is implemented whereas, in a priority +queue, the values are removed on the basis of priority. The element with the +highest priority is removed first. -insert() - Would insert an element in a queue +insert() - Would insert an element in a queue delete() - Would delete the smallest element in the queue */ +#include +#include +#define NULL ((void *)0) -#include -#include -#define NULL ((void*)0) - -struct node +struct node { - int data ; - struct node *next ; -} ; + int data; + struct node *next; +}; -struct node *front , *rear ; +struct node *front, *rear; -/* This function initializes the queue to empty by making both front and rear as NULL */ -void createqueue() +/* This function initializes the queue to empty by making both front and rear as + * NULL */ +void createqueue() { front = rear = NULL; } + +int empty() { - front=rear=NULL ; + if (front == NULL) + return 1; + else + return 0; } -int empty() +void insert(int x) { - if(front==NULL) - return 1 ; - else - return 0 ; -} + struct node *pnode; -void insert(int x) -{ - struct node *pnode ; - - pnode=(struct node*)malloc(sizeof(struct node)) ; - if(pnode==NULL) - { - printf("Memory overflow. Unable to insert.\n") ; - exit(1) ; - } - - pnode->data=x ; - pnode->next=NULL; /* New node is always last node */ - - if(empty()) - front=rear=pnode ; - else - { - rear->next=pnode ; - rear=pnode ; - } -} - -int removes() -{ - int min ; - struct node *follow , *follow1 , *p , *p1 ; - - if(empty()) - { - printf("\nQueue Underflow. Unable to remove.") ; - exit(1) ; - } - - /* finding the node with minimum value in the APQ.*/ - p=p1=front ; - follow=follow1=NULL ; - min=front->data ; - while(p!=NULL) - { - if(p->datadata ; - follow1=follow ; - p1=p ; - } - follow=p ; - p=p->next ; - } - - /* Deleting the node with min value */ - - if(p1==front) /* deleting first node.*/ - { - front=front->next ; - if(front==NULL) /* Deleting the only one node */ - rear=NULL ; - } - else if(p1==rear) /* Deleting last node */ - { - rear=follow1 ; - rear->next=NULL ; - } - else /* deleting any other node.*/ - follow1->next=p1->next ; - - - free(p1) ; - return min ; /* DONT FORGET LAST 2 STATEMENTS.*/ -} - -void show() -{ - struct node *p ; - - if(empty()) - printf("Queue empty. No data to display \n") ; - else - { - printf("Queue from front to rear is as shown: \n") ; - - p=front ; - while(p!=NULL) - { - printf("%d ",p->data) ; - p=p->next ; + printf("Memory overflow. Unable to insert.\n"); + exit(1); } - printf("\n") ; - } -} + pnode->data = x; + pnode->next = NULL; /* New node is always last node */ -void destroyqueue() -{ - front=rear=NULL ; -} - -int main() -{ - int x , ch ; - - createqueue() ; - - - do - { - printf("\n\n Menu: \n") ; - printf("1:Insert \n") ; - printf("2:Remove \n") ; - printf("3:exit \n") ; - printf("Enter your choice: ") ; - scanf("%d",&ch) ; - - switch(ch) + if (empty()) + front = rear = pnode; + else { - case 1: - printf("Enter element to be inserted: ") ; - scanf("%d",&x) ; - insert(x) ; - show() ; - break ; - - case 2: - x=removes() ; - printf("Element removed is: %d\n",x) ; - show() ; - break ; - - case 3: - break ; + rear->next = pnode; + rear = pnode; } - } - while(ch!=3) ; +} - destroyqueue() ; +int removes() +{ + int min; + struct node *follow, *follow1, *p, *p1; - return 0; + if (empty()) + { + printf("\nQueue Underflow. Unable to remove."); + exit(1); + } + + /* finding the node with minimum value in the APQ.*/ + p = p1 = front; + follow = follow1 = NULL; + min = front->data; + while (p != NULL) + { + if (p->data < min) + { + min = p->data; + follow1 = follow; + p1 = p; + } + follow = p; + p = p->next; + } + + /* Deleting the node with min value */ + + if (p1 == front) /* deleting first node.*/ + { + front = front->next; + if (front == NULL) /* Deleting the only one node */ + rear = NULL; + } + else if (p1 == rear) /* Deleting last node */ + { + rear = follow1; + rear->next = NULL; + } + else /* deleting any other node.*/ + follow1->next = p1->next; + + free(p1); + return min; /* DONT FORGET LAST 2 STATEMENTS.*/ +} + +void show() +{ + struct node *p; + + if (empty()) + printf("Queue empty. No data to display \n"); + else + { + printf("Queue from front to rear is as shown: \n"); + + p = front; + while (p != NULL) + { + printf("%d ", p->data); + p = p->next; + } + + printf("\n"); + } +} + +void destroyqueue() { front = rear = NULL; } + +int main() +{ + int x, ch; + + createqueue(); + + do + { + printf("\n\n Menu: \n"); + printf("1:Insert \n"); + printf("2:Remove \n"); + printf("3:exit \n"); + printf("Enter your choice: "); + scanf("%d", &ch); + + switch (ch) + { + case 1: + printf("Enter element to be inserted: "); + scanf("%d", &x); + insert(x); + show(); + break; + + case 2: + x = removes(); + printf("Element removed is: %d\n", x); + show(); + break; + + case 3: + break; + } + } while (ch != 3); + + destroyqueue(); + + return 0; } /* Output of the Program*/ diff --git a/data_structures/linked_list/merge_linked_lists.c b/data_structures/linked_list/merge_linked_lists.c index 0f95ff4e..2bba2575 100644 --- a/data_structures/linked_list/merge_linked_lists.c +++ b/data_structures/linked_list/merge_linked_lists.c @@ -1,8 +1,9 @@ -#include -#include -struct node{ - int data; - struct node *next; +#include +#include +struct node +{ + int data; + struct node *next; }; struct node *head1 = NULL; @@ -12,37 +13,44 @@ struct node *head2 = NULL; void merge() { - struct node *temp1 = head1; - struct node *temp2 = head2; + struct node *temp1 = head1; + struct node *temp2 = head2; - struct node *holder1 = NULL; - struct node *holder2 = NULL; - //Temporary pointer variables to store the address of next node of the two input linked list + struct node *holder1 = NULL; + struct node *holder2 = NULL; + // Temporary pointer variables to store the address of next node of the two + // input linked list - while(temp1!=NULL && temp2!=NULL) - { - holder1 = temp1 -> next; - //Storing the address of next node of first linked list - temp1->next=temp2; - //Making the first node of first linked list point to first node of second linked list + while (temp1 != NULL && temp2 != NULL) + { + holder1 = temp1->next; + // Storing the address of next node of first linked list + temp1->next = temp2; + // Making the first node of first linked list point to first node of + // second linked list - if(holder1!=NULL) { - //Making the first node of second linked list point to second node of first linked list - holder2 = temp2 -> next; - temp2 -> next = holder1; - } - temp1=holder1; - temp2=holder2; - //Updating the address location of two pointer variables temp1 and temp2 - } + if (holder1 != NULL) + { + // Making the first node of second linked list point to second node + // of first linked list + holder2 = temp2->next; + temp2->next = holder1; + } + temp1 = holder1; + temp2 = holder2; + // Updating the address location of two pointer variables temp1 and + // temp2 + } } -void printlist(struct node *temp){ - printf("%d",temp->data); - temp=temp->next; - while(temp!=NULL){ - printf("->%d",temp->data); - temp=temp->next; +void printlist(struct node *temp) +{ + printf("%d", temp->data); + temp = temp->next; + while (temp != NULL) + { + printf("->%d", temp->data); + temp = temp->next; } printf("\n"); } @@ -51,53 +59,53 @@ int main() { // Linked List 1: 1->3->5->7 : Linked List 2: 2->4->6 // making lists - struct node *one = (struct node*)malloc(sizeof(struct node)); - struct node *two = (struct node*)malloc(sizeof(struct node)); - struct node *three = (struct node*)malloc(sizeof(struct node)); - struct node *four = (struct node*)malloc(sizeof(struct node)); - struct node *five = (struct node*)malloc(sizeof(struct node)); - struct node *six = (struct node*)malloc(sizeof(struct node)); - struct node *seven = (struct node*)malloc(sizeof(struct node)); - //Seven nodes are created + struct node *one = (struct node *)malloc(sizeof(struct node)); + struct node *two = (struct node *)malloc(sizeof(struct node)); + struct node *three = (struct node *)malloc(sizeof(struct node)); + struct node *four = (struct node *)malloc(sizeof(struct node)); + struct node *five = (struct node *)malloc(sizeof(struct node)); + struct node *six = (struct node *)malloc(sizeof(struct node)); + struct node *seven = (struct node *)malloc(sizeof(struct node)); + // Seven nodes are created - head1=one; - head2=two; - //head1 points to first node of first linked list - //head2 points to first node of second linked list + head1 = one; + head2 = two; + // head1 points to first node of first linked list + // head2 points to first node of second linked list - one->data=1; - one->next=three; + one->data = 1; + one->next = three; - two->data=2; - two->next=four; + two->data = 2; + two->next = four; - three->data=3; - three->next=five; + three->data = 3; + three->next = five; - four->data=4; - four->next=six; + four->data = 4; + four->next = six; - five->data=5; - five->next=seven; + five->data = 5; + five->next = seven; - six->data=6; - six->next=NULL; - //Last node of second input linked list + six->data = 6; + six->next = NULL; + // Last node of second input linked list - seven->data=7; - seven->next=NULL; - //Last node of first input linked list + seven->data = 7; + seven->next = NULL; + // Last node of first input linked list - printf("Linked List 1: "); - printlist(head1); - printf("\nLinked List 2: "); - printlist(head2); + printf("Linked List 1: "); + printlist(head1); + printf("\nLinked List 2: "); + printlist(head2); - //Merging the two linked list into single linked list - merge(); + // Merging the two linked list into single linked list + merge(); - printf("\nMerged Linked List: "); - printlist(head1); //list one has been modified + printf("\nMerged Linked List: "); + printlist(head1); // list one has been modified - return 0; + return 0; } diff --git a/data_structures/linked_list/middle_element_in_list.c b/data_structures/linked_list/middle_element_in_list.c index 310d6a93..3437ce4b 100644 --- a/data_structures/linked_list/middle_element_in_list.c +++ b/data_structures/linked_list/middle_element_in_list.c @@ -1,70 +1,69 @@ -#include -#include +#include +#include /* Link list node */ -struct Node -{ - int data; - struct Node* next; -}; +struct Node +{ + int data; + struct Node *next; +}; /* Function to get the middle of the linked list*/ -void printMiddle(struct Node *head) -{ - struct Node *slow_ptr = head; - struct Node *fast_ptr = head; +void printMiddle(struct Node *head) +{ + struct Node *slow_ptr = head; + struct Node *fast_ptr = head; - if (head!=NULL) - { - while (fast_ptr != NULL && fast_ptr->next != NULL) - { - fast_ptr = fast_ptr->next->next; - slow_ptr = slow_ptr->next; - } - printf("The middle element is [%d]\n\n", slow_ptr->data); - } -} + if (head != NULL) + { + while (fast_ptr != NULL && fast_ptr->next != NULL) + { + fast_ptr = fast_ptr->next->next; + slow_ptr = slow_ptr->next; + } + printf("The middle element is [%d]\n\n", slow_ptr->data); + } +} -void push(struct Node** head_ref, int new_data) -{ - /* allocate node */ - struct Node* new_node = - (struct Node*) malloc(sizeof(struct Node)); +void push(struct Node **head_ref, int new_data) +{ + /* allocate node */ + struct Node *new_node = (struct Node *)malloc(sizeof(struct Node)); - /* put in the data */ - new_node->data = new_data; + /* put in the data */ + new_node->data = new_data; - /* link the old list off the new node */ - new_node->next = (*head_ref); + /* link the old list off the new node */ + new_node->next = (*head_ref); - /* move the head to point to the new node */ - (*head_ref) = new_node; -} + /* move the head to point to the new node */ + (*head_ref) = new_node; +} -// A utility function to print a given linked list -void printList(struct Node *ptr) -{ - while (ptr != NULL) - { - printf("%d->", ptr->data); - ptr = ptr->next; - } - printf("NULL\n"); -} +// A utility function to print a given linked list +void printList(struct Node *ptr) +{ + while (ptr != NULL) + { + printf("%d->", ptr->data); + ptr = ptr->next; + } + printf("NULL\n"); +} /* Drier program to test above function*/ -int main() -{ - /* Start with the empty list */ - struct Node* head = NULL; - int i; +int main() +{ + /* Start with the empty list */ + struct Node *head = NULL; + int i; - for (i=5; i>0; i--) - { - push(&head, i); - printList(head); - printMiddle(head); - } + for (i = 5; i > 0; i--) + { + push(&head, i); + printList(head); + printMiddle(head); + } - return 0; -} + return 0; +} diff --git a/data_structures/linked_list/queue_linked_list.c b/data_structures/linked_list/queue_linked_list.c index d9076fdb..5074edea 100644 --- a/data_structures/linked_list/queue_linked_list.c +++ b/data_structures/linked_list/queue_linked_list.c @@ -1,149 +1,141 @@ -/* Queue using Linked List - Program to create a queue ADT using linked list. ADT should support the following operations -1) Createqueue -2) Insert into the queue -3) Delete from the queue -4) destroyqueue +/* Queue using Linked List - Program to create a queue ADT using linked list. +ADT should support the following operations 1) Createqueue 2) Insert into the +queue 3) Delete from the queue 4) destroyqueue */ /* queue q declared globally */ #include #include -#define NULL 0 +#define NULL 0 -struct node +struct node { - int data ; - struct node *next ; -} ; + int data; + struct node *next; +}; -struct queue +struct queue { - struct node *front , *rear ; -} ; + struct node *front, *rear; +}; -struct queue q ; +struct queue q; -/* This function initializes the queue to empty by making both front and rear as NULL */ -void createqueue() +/* This function initializes the queue to empty by making both front and rear as + * NULL */ +void createqueue() { q.front = q.rear = NULL; } + +int empty() { - q.front=q.rear=NULL ; + if (q.front == NULL) + return 1; + else + return 0; } -int empty() +void insert(int x) { - if(q.front==NULL) - return 1 ; - else - return 0 ; -} + struct node *pnode; -void insert(int x) -{ - struct node *pnode ; - - pnode=(struct node*)malloc(sizeof(struct node)) ; - if(pnode==NULL) - { - printf("Memory overflow. Unable to insert.\n") ; - exit(1) ; - } - - pnode->data=x ; - pnode->next=NULL ; /* New node is always last node */ - - if(empty()) - q.front=q.rear=pnode ; - else - { - (q.rear)->next=pnode ; - q.rear=pnode ; - } -} - -int removes() -{ - int x ; - struct node *p ; - - if(empty()) - { - printf("Queue Underflow. Unable to remove.\n") ; - exit(1) ; - } - - p=q.front ; - x=(q.front)->data ; - q.front=(q.front)->next ; - if(q.front==NULL) /* Queue contained only one node */ - q.rear=NULL ; - free(p) ; - return x ; -} - -void show() -{ - struct node *p ; - - if(empty()) - printf("Queue empty. No data to display \n") ; - else - { - printf("Queue from front to rear is as shown: \n") ; - - p=q.front ; - while(p!=NULL) + pnode = (struct node *)malloc(sizeof(struct node)); + if (pnode == NULL) { - printf("%d ",p->data) ; - p=p->next ; + printf("Memory overflow. Unable to insert.\n"); + exit(1); } - printf("\n") ; - } + pnode->data = x; + pnode->next = NULL; /* New node is always last node */ + + if (empty()) + q.front = q.rear = pnode; + else + { + (q.rear)->next = pnode; + q.rear = pnode; + } } -void destroyqueue() +int removes() { - q.front=q.rear=NULL ; + int x; + struct node *p; + + if (empty()) + { + printf("Queue Underflow. Unable to remove.\n"); + exit(1); + } + + p = q.front; + x = (q.front)->data; + q.front = (q.front)->next; + if (q.front == NULL) /* Queue contained only one node */ + q.rear = NULL; + free(p); + return x; } +void show() +{ + struct node *p; + + if (empty()) + printf("Queue empty. No data to display \n"); + else + { + printf("Queue from front to rear is as shown: \n"); + + p = q.front; + while (p != NULL) + { + printf("%d ", p->data); + p = p->next; + } + + printf("\n"); + } +} + +void destroyqueue() { q.front = q.rear = NULL; } + int main() { - int x , ch ; + int x, ch; - createqueue() ; + createqueue(); - do - { - printf("\n\n Menu: \n") ; - printf("1:Insert \n") ; - printf("2:Remove \n") ; - printf("3:exit \n") ; - printf("Enter your choice: ") ; - scanf("%d",&ch) ; - - switch(ch) + do { - case 1: - printf("Enter element to be inserted: ") ; - scanf("%d",&x) ; - insert(x) ; - show() ; - break ; + printf("\n\n Menu: \n"); + printf("1:Insert \n"); + printf("2:Remove \n"); + printf("3:exit \n"); + printf("Enter your choice: "); + scanf("%d", &ch); - case 2: - x=removes() ; - printf("Element removed is: %d\n",x) ; - show() ; - break ; + switch (ch) + { + case 1: + printf("Enter element to be inserted: "); + scanf("%d", &x); + insert(x); + show(); + break; - case 3: - break ; - } - } - while(ch!=3) ; + case 2: + x = removes(); + printf("Element removed is: %d\n", x); + show(); + break; - destroyqueue() ; + case 3: + break; + } + } while (ch != 3); - return 0; + destroyqueue(); + + return 0; } diff --git a/data_structures/linked_list/singly_link_list_deletion.c b/data_structures/linked_list/singly_link_list_deletion.c index 4a725233..83a05107 100644 --- a/data_structures/linked_list/singly_link_list_deletion.c +++ b/data_structures/linked_list/singly_link_list_deletion.c @@ -1,69 +1,71 @@ -/*Includes structure for a node which can be use to make new nodes of the Linked List. - It is assumed that the data in nodes will be an integer, though - function can be modified according to the data type, easily. - deleteNode deletes a node when passed with a key of the node. +/*Includes structure for a node which can be use to make new nodes of the Linked + List. It is assumed that the data in nodes will be an integer, though function + can be modified according to the data type, easily. deleteNode deletes a node + when passed with a key of the node. */ -#include +#include struct node -{int info; - struct node *link; +{ + int info; + struct node *link; }; -struct node *start=NULL; +struct node *start = NULL; /////////////////////////////////////////////////////////// -struct node * createnode()//function to create node -{ - struct node *t; - t=(struct node*)malloc(sizeof(struct node)); - return(t); -} -//////////////////////////////////////////////////////// -void insert()//function to insert at first location -{ - struct node *p; - p=createnode(); - printf("\nenter the number to insert"); - scanf("%d",&p->info); - p->link=NULL; - if(start==NULL) - { - start=p; - } - else - { - p->link=start; - start=p; - } -} -/////////////////////////////////////////////////////////// -void deletion()//function to delete from first position +struct node *createnode() // function to create node { struct node *t; - if(start==NULL) + t = (struct node *)malloc(sizeof(struct node)); + return (t); +} +//////////////////////////////////////////////////////// +void insert() // function to insert at first location +{ + struct node *p; + p = createnode(); + printf("\nenter the number to insert"); + scanf("%d", &p->info); + p->link = NULL; + if (start == NULL) + { + start = p; + } + else + { + p->link = start; + start = p; + } +} +/////////////////////////////////////////////////////////// +void deletion() // function to delete from first position +{ + struct node *t; + if (start == NULL) { printf("\nlist is empty"); } else { struct node *p; - p=start; - start=start->link; + p = start; + start = start->link; free(p); } } /////////////////////////////////////////////////////// -void viewlist()//function to display values +void viewlist() // function to display values { struct node *p; - if(start==NULL) + if (start == NULL) { printf("\nlist is empty"); } else - { p=start; - while(p!=NULL) + { + p = start; + while (p != NULL) { - printf("%d ",p->info); - p=p->link; + printf("%d ", p->info); + p = p->link; } } } @@ -72,14 +74,14 @@ void viewlist()//function to display values int main() { int n; - while(1) + while (1) { printf("\n1.add value at first location"); printf("\n2.delete value from first location"); printf("\n3.view value"); printf("\nenter your choice"); - scanf("%d",&n); - switch(n) + scanf("%d", &n); + switch (n) { case 1: insert(); @@ -94,5 +96,5 @@ int main() printf("\ninvalid choice"); } } - return(0); + return (0); } diff --git a/data_structures/linked_list/stack_using_linked_lists.c b/data_structures/linked_list/stack_using_linked_lists.c index 7945af70..ef3f7cb0 100644 --- a/data_structures/linked_list/stack_using_linked_lists.c +++ b/data_structures/linked_list/stack_using_linked_lists.c @@ -1,92 +1,85 @@ -#include -#include +#include +#include struct node { - int info; - struct node *link; + int info; + struct node *link; }; -struct node *top=NULL,*temp; -void push(struct node*); -void pop(struct node*); -void display(struct node*); +struct node *top = NULL, *temp; +void push(struct node *); +void pop(struct node *); +void display(struct node *); int main() -{ - int x=0,item; - printf("\t****stack using linked list****\n"); - while(x!=4) - { - printf("enter your choice"); - printf("\n1.push\n2.pop\n3.display\n4.exit\n"); - scanf("%d",&x); - switch(x) - { - case 1: - push(top); - break; - case 2: pop(top); - break; - case 3: display(top); - break; - case 4: return 0; - - } - } - +{ + int x = 0, item; + printf("\t****stack using linked list****\n"); + while (x != 4) + { + printf("enter your choice"); + printf("\n1.push\n2.pop\n3.display\n4.exit\n"); + scanf("%d", &x); + switch (x) + { + case 1: + push(top); + break; + case 2: + pop(top); + break; + case 3: + display(top); + break; + case 4: + return 0; + } + } } void push(struct node *p) { - int item; - struct node *temp; - temp=(struct node *)malloc(sizeof(struct node)); - printf("enter element to be inserted\n"); - scanf("%d",&item); - temp->info=item; - + int item; + struct node *temp; + temp = (struct node *)malloc(sizeof(struct node)); + printf("enter element to be inserted\n"); + scanf("%d", &item); + temp->info = item; - - temp->link=top; - top=temp; - - + temp->link = top; + top = temp; - printf("inserted succesfully\n"); + printf("inserted succesfully\n"); } void pop(struct node *p) { - int item; - struct node *temp; - - if(top==NULL) - printf("stack is empty\n"); - else{ - item=top->info; - temp=top; - top=top->link; - free(temp); - printf("Element popped is%d\n",item); - } - -} + int item; + struct node *temp; + if (top == NULL) + printf("stack is empty\n"); + else + { + item = top->info; + temp = top; + top = top->link; + free(temp); + printf("Element popped is%d\n", item); + } +} void display(struct node *p) { - - if(top==NULL) - printf("stack is empty\n"); - else - { printf("Elements in the stack are\n"); - while(p!=NULL) - { - printf("%d\n",p->info); - p=p->link; - } + + if (top == NULL) + printf("stack is empty\n"); + else + { + printf("Elements in the stack are\n"); + while (p != NULL) + { + printf("%d\n", p->info); + p = p->link; + } // printf("%d\n",p->info); - - } - + } } - - diff --git a/data_structures/list/list.c b/data_structures/list/list.c index 864af814..40764321 100644 --- a/data_structures/list/list.c +++ b/data_structures/list/list.c @@ -1,22 +1,24 @@ +#include "list.h" #include +#include #include #include #include -#include -#include "list.h" #define L List_T /* Initial list */ -L List_init (void) { +L List_init(void) +{ L list; - list = (L) malloc(sizeof(L)); + list = (L)malloc(sizeof(L)); list->next = NULL; return list; } /* Push an element into top of the list */ -L List_push(L list, void *val) { +L List_push(L list, void *val) +{ L new_elem = (L)malloc(sizeof(L)); new_elem->val = val; new_elem->next = list; @@ -24,19 +26,22 @@ L List_push(L list, void *val) { } /* Length of list */ -int List_length(L list) { +int List_length(L list) +{ int n; - for(n = 0; list; list=list->next) + for (n = 0; list; list = list->next) n++; return n; } /* Convert list to array */ -void **List_toArray(L list) { +void **List_toArray(L list) +{ int i, n = List_length(list); - void **array = (void **)malloc((n+1) *sizeof(*array)); + void **array = (void **)malloc((n + 1) * sizeof(*array)); - for(i = 0; i < n; i++) { + for (i = 0; i < n; i++) + { array[i] = list->val; list = list->next; } @@ -45,12 +50,14 @@ void **List_toArray(L list) { } /* Create and return a list */ -L List_list(L list, void *val, ...) { +L List_list(L list, void *val, ...) +{ va_list ap; L *p = &list; va_start(ap, val); - for(; val; val = va_arg(ap, void *)) { + for (; val; val = va_arg(ap, void *)) + { *p = malloc(sizeof(L)); (*p)->val = val; p = &(*p)->next; @@ -61,13 +68,14 @@ L List_list(L list, void *val, ...) { } /* Append 2 lists together */ -L List_append(L list, L tail) { +L List_append(L list, L tail) +{ L *p = &list; - while((*p)->next) { + while ((*p)->next) + { p = &(*p)->next; } *p = tail; return list; } - diff --git a/data_structures/list/list.h b/data_structures/list/list.h index 8d579a86..3d31f42d 100644 --- a/data_structures/list/list.h +++ b/data_structures/list/list.h @@ -4,20 +4,21 @@ #define L List_T typedef struct L *L; -struct L { +struct L +{ void *val; L next; }; -extern L List_init(void); -extern L List_push(L list, void *val); -extern int List_length(L list); +extern L List_init(void); +extern L List_push(L list, void *val); +extern int List_length(L list); extern void **List_toArray(L list); -extern L List_append(L list, L tail); -extern L List_list(L list, void *val, ...); +extern L List_append(L list, L tail); +extern L List_list(L list, void *val, ...); /* TODO */ -extern L List_copy(L list); -extern int List_pop(L *list); +extern L List_copy(L list); +extern int List_pop(L *list); #undef L #endif diff --git a/data_structures/list/main.c b/data_structures/list/main.c index c31fdba9..524ed6ee 100644 --- a/data_structures/list/main.c +++ b/data_structures/list/main.c @@ -1,19 +1,21 @@ +#include "list.h" +#include #include #include -#include #include -#include "list.h" -void print_list(char **array) { +void print_list(char **array) +{ int i; - for( i = 0; array[i]; i++) + for (i = 0; array[i]; i++) printf("%s", array[i]); printf("\n"); } -int main() { +int main() +{ List_T list1, list2, list3; - char **str1 = (char **)malloc(100* sizeof(char *)); + char **str1 = (char **)malloc(100 * sizeof(char *)); list1 = List_init(); list1 = List_push(list1, "Dang "); diff --git a/data_structures/queue.c b/data_structures/queue.c index df4d91f9..e2a7fcb6 100644 --- a/data_structures/queue.c +++ b/data_structures/queue.c @@ -1,25 +1,26 @@ //////////////////////////////////////////////////////////////////////////////// -//INCLUDES +// INCLUDES #include #include //////////////////////////////////////////////////////////////////////////////// -//MACROS: CONSTANTS +// MACROS: CONSTANTS //////////////////////////////////////////////////////////////////////////////// -//DATA STRUCTURES -struct node { +// DATA STRUCTURES +struct node +{ int data; - struct node* next; - struct node* pre; -} *head, *tail, *tmp; + struct node *next; + struct node *pre; +} * head, *tail, *tmp; //////////////////////////////////////////////////////////////////////////////// -//GLOBAL VARIABLES +// GLOBAL VARIABLES int count; //////////////////////////////////////////////////////////////////////////////// -//FORWARD DECLARATIONS +// FORWARD DECLARATIONS void create(); void enque(int x); int deque(); @@ -28,19 +29,19 @@ int size(); int isEmpty(); //////////////////////////////////////////////////////////////////////////////// -//MAIN ENTRY POINT +// MAIN ENTRY POINT -int main(int argc, char const *argv[]) { +int main(int argc, char const *argv[]) +{ create(); enque(5); - - return 0; + return 0; } - -void create() { +void create() +{ head = NULL; tail = NULL; } @@ -48,13 +49,17 @@ void create() { /** * Puts an item into the Queue. */ -void enque(int x) { - if(head == NULL) { +void enque(int x) +{ + if (head == NULL) + { head = (struct node *)malloc(1 * sizeof(struct node)); head->data = x; head->pre = NULL; tail = head; - } else { + } + else + { tmp = (struct node *)malloc(1 * sizeof(struct node)); tmp->data = x; tmp->next = tail; @@ -65,25 +70,27 @@ void enque(int x) { /** * Takes the next item from the Queue. */ -int deque() { +int deque() +{ int returnData = 0; - if(head == NULL) { + if (head == NULL) + { printf("ERROR: Deque from empty queue.\n"); exit(1); - } else { + } + else + { returnData = head->data; - if(head->pre == NULL) + if (head->pre == NULL) head = NULL; else head = head->pre; head->next = NULL; } - return returnData; + return returnData; } /** * Returns the size of the Queue. */ -int size() { - return count; -} \ No newline at end of file +int size() { return count; } \ No newline at end of file diff --git a/data_structures/stack.c b/data_structures/stack.c index b0504607..a17e8d0b 100644 --- a/data_structures/stack.c +++ b/data_structures/stack.c @@ -4,27 +4,28 @@ */ //////////////////////////////////////////////////////////////////////////////// -//INCLUDES +// INCLUDES #include #include //////////////////////////////////////////////////////////////////////////////// -//MACROS: CONSTANTS +// MACROS: CONSTANTS //////////////////////////////////////////////////////////////////////////////// -//DATA STRUCTURES -struct node { +// DATA STRUCTURES +struct node +{ int data; - struct node* next; - struct node* pre; -} *head, *tmp; + struct node *next; + struct node *pre; +} * head, *tmp; //////////////////////////////////////////////////////////////////////////////// -//GLOBAL VARIABLES +// GLOBAL VARIABLES int count = 0; //////////////////////////////////////////////////////////////////////////////// -//FUNCTION PROTOTYPES +// FUNCTION PROTOTYPES void create(); void push(int x); int pop(); @@ -33,9 +34,10 @@ int size(); int isEmpty(); //////////////////////////////////////////////////////////////////////////////// -//MAIN ENTRY POINT +// MAIN ENTRY POINT -int main(int argc, char const *argv[]) { +int main(int argc, char const *argv[]) +{ int x, y, z; @@ -52,7 +54,7 @@ int main(int argc, char const *argv[]) { y = pop(); // 3, 2. Count: 1. Empty: 0; printf("%d, %d.\t\tCount: %d.\tEmpty: %d.\n", x, y, size(), isEmpty()); - pop(); // Empty the stack. + pop(); // Empty the stack. push(5); push(6); @@ -64,26 +66,28 @@ int main(int argc, char const *argv[]) { // 1, 6, 7, 8. Count: 2. Empty: 0. printf("%d, %d, %d.\tCount: %d.\tEmpty: %d.\n", x, y, z, size(), isEmpty()); - return 0; + return 0; } /** * Initialize the stack to NULL. */ -void create() { - head = NULL; -} +void create() { head = NULL; } /** * Push data onto the stack. */ -void push(int x) { - if(head == NULL) { +void push(int x) +{ + if (head == NULL) + { head = (struct node *)malloc(1 * sizeof(struct node)); head->next = NULL; head->pre = NULL; head->data = x; - } else { + } + else + { tmp = (struct node *)malloc(1 * sizeof(struct node)); tmp->data = x; tmp->next = NULL; @@ -97,19 +101,25 @@ void push(int x) { /** * Pop data from the stack */ -int pop() { +int pop() +{ int returnData; - if(head == NULL) { + if (head == NULL) + { printf("ERROR: Pop from empty stack.\n"); exit(1); - } else { + } + else + { returnData = head->data; - if(head->pre == NULL){ + if (head->pre == NULL) + { free(head); head = NULL; } - else { + else + { head = head->pre; free(head->next); } @@ -121,10 +131,12 @@ int pop() { /** * Returns the next value to be popped. */ -int peek() { - if(head != NULL) +int peek() +{ + if (head != NULL) return head->data; - else { + else + { printf("ERROR: Peeking from empty stack."); exit(1); } @@ -133,15 +145,14 @@ int peek() { /** * Returns the size of the stack. */ -int size() { - return count; -} +int size() { return count; } /** * Returns 1 if stack is empty, returns 0 if not empty. */ -int isEmpty() { - if(count == 0) +int isEmpty() +{ + if (count == 0) return 1; return 0; } diff --git a/data_structures/stack/main.c b/data_structures/stack/main.c index 6a1502bb..2886f1cc 100644 --- a/data_structures/stack/main.c +++ b/data_structures/stack/main.c @@ -1,4 +1,4 @@ -//program for stack using array +// program for stack using array #include @@ -45,7 +45,7 @@ int main() return (0); } -//function for pushing the element +// function for pushing the element void push() { int n = 0; @@ -55,7 +55,7 @@ void push() a[top] = n; } -//function for poping the element out +// function for poping the element out void pop() { if (top == -1) @@ -71,7 +71,7 @@ void pop() } } -//function for peeping the element from top of the stack +// function for peeping the element from top of the stack void peek() { if (top >= 0) @@ -80,7 +80,7 @@ void peek() printf("\nstack is empty"); } -//function to update the element of stack +// function to update the element of stack void update() { int i, n; diff --git a/data_structures/stack/parenthesis.c b/data_structures/stack/parenthesis.c index 993f2edd..58de28db 100644 --- a/data_structures/stack/parenthesis.c +++ b/data_structures/stack/parenthesis.c @@ -1,7 +1,7 @@ +#include #include #include #include -#include #define SIZE 100 @@ -12,14 +12,15 @@ struct node }; int c = 0; // c used as counter to check if stack is empty or not -struct node *head; //declaring head pointer globally assigned to NULL +struct node *head; // declaring head pointer globally assigned to NULL -void push(char x) //function for pushing +void push(char x) // function for pushing { struct node *p = head, *temp; temp = (struct node *)malloc(sizeof(struct node)); temp->data = x; - if (head == NULL) //will be execute only one time i.e, 1st time push is called + if (head == + NULL) // will be execute only one time i.e, 1st time push is called { head = temp; p = head; @@ -35,7 +36,7 @@ void push(char x) //function for pushing } } -char pop(void) //function for pop +char pop(void) // function for pop { char x; struct node *p = head; @@ -50,14 +51,16 @@ int isBalanced(char *s) { int i = 0; char x; - while (s[i] != '\0') //loop for covering entire string of brackets + while (s[i] != '\0') // loop for covering entire string of brackets { // printf("\t s[i]=%c\n", s[i]); //DEBUG - if (s[i] == '{' || s[i] == '(' || s[i] == '[') //if opening bracket then push + if (s[i] == '{' || s[i] == '(' || + s[i] == '[') // if opening bracket then push push(s[i]); else { - if (c <= 0) //i.e, stack is empty as only opening brackets are added to stack + if (c <= 0) // i.e, stack is empty as only opening brackets are + // added to stack return 0; x = pop(); @@ -71,7 +74,8 @@ int isBalanced(char *s) i++; } - //at end if stack is empy which means whole process has been performed correctly so return 1 + // at end if stack is empy which means whole process has been performed + // correctly so return 1 return (c == 0) ? 1 : 0; } diff --git a/data_structures/stack/stack.c b/data_structures/stack/stack.c index e18c10be..93bf0e34 100644 --- a/data_structures/stack/stack.c +++ b/data_structures/stack/stack.c @@ -6,15 +6,15 @@ of data hiding. */ +#include #include #include -#include #include "stack.h" -/* +/* actual stack data structure - This pointer will pointing at the actual field (of void * pointers) + This pointer will pointing at the actual field (of void * pointers) that represents the stack. */ void **array; @@ -25,8 +25,8 @@ int max = 10; /* counter variable for counting the elements of the stack. */ int counter = 0; -/* - offset address +/* + offset address points at the top element of the stack. */ int offset = -1; @@ -42,7 +42,7 @@ void initStack() grow: increases the stack by 10 elements. This utility function isn't part of the public interface */ -void grow() +void grow() { max += 10; /* increases the capacity */ @@ -56,7 +56,7 @@ void grow() } /*free the memory */ free(array); - array = tmp; + array = tmp; } /* push: pushs the argument onto the stack */ @@ -70,9 +70,9 @@ void push(void *object) offset++; /* increases the element-pointer */ - /* - moves pointer by the offset address - pushs the object onto stack + /* + moves pointer by the offset address + pushs the object onto stack */ *(array + offset) = object; @@ -82,7 +82,7 @@ void push(void *object) else /* stack is full */ { - grow(); /* lets grow stack */ + grow(); /* lets grow stack */ push(object); /* recursive call */ } } @@ -114,18 +114,12 @@ void *pop() /* size: gets the number of elements of the stack. */ -int size() -{ - return counter; -} +int size() { return counter; } /* isEmpty(): returns 1 if stack is empty otherwise 0. */ -int isEmpty() -{ - return counter == 0; -} +int isEmpty() { return counter == 0; } /* top: returns the top element from the stack without removing it. diff --git a/data_structures/stack/stack.h b/data_structures/stack/stack.h index 5af106a9..03703b95 100644 --- a/data_structures/stack/stack.h +++ b/data_structures/stack/stack.h @@ -2,10 +2,9 @@ author: Christian Bender This header represents the public stack-interface. - The stack is generic and self growing. + The stack is generic and self growing. */ - #ifndef __STACK__ #define __STACK__ @@ -15,15 +14,15 @@ void initStack(); /* - push: pushs the argument onto the stack + push: pushs the argument onto the stack */ -void push(void * object); +void push(void *object); /* pop: pops the top element of the stack from the stack. assumes: stack not empty. */ -void * pop(); +void *pop(); /* size: gets the number of elements of the stack. @@ -38,6 +37,6 @@ int isEmpty(); /* top: returns the top element from the stack without removing it. */ -void * top(); +void *top(); #endif \ No newline at end of file diff --git a/data_structures/stack/stack_linked_list/main.c b/data_structures/stack/stack_linked_list/main.c index 2e599e9a..34d0429e 100644 --- a/data_structures/stack/stack_linked_list/main.c +++ b/data_structures/stack/stack_linked_list/main.c @@ -1,15 +1,16 @@ +#include "stack.h" +#include #include #include -#include -#include "stack.h" -int main() { +int main() +{ Stack_T stk; stk = Stack_init(); - Stack_push(stk, (int *) 1); - Stack_push(stk, (int *) 2); - Stack_push(stk, (int *) 3); - Stack_push(stk, (int *) 4); + Stack_push(stk, (int *)1); + Stack_push(stk, (int *)2); + Stack_push(stk, (int *)3); + Stack_push(stk, (int *)4); printf("Size: %d\n", Stack_size(stk)); Stack_print(stk); Stack_pop(stk); diff --git a/data_structures/stack/stack_linked_list/stack.c b/data_structures/stack/stack_linked_list/stack.c index 4668d694..cd02b6eb 100644 --- a/data_structures/stack/stack_linked_list/stack.c +++ b/data_structures/stack/stack_linked_list/stack.c @@ -1,48 +1,54 @@ +#include "stack.h" #include #include -#include #include -#include "stack.h" +#include #define T Stack_T -typedef struct elem { +typedef struct elem +{ void *val; struct elem *next; } elem_t; -struct T { +struct T +{ int count; elem_t *head; }; /* Initial stack */ -T Stack_init (void) { +T Stack_init(void) +{ T stack; - stack = (T) malloc(sizeof(T)); + stack = (T)malloc(sizeof(T)); stack->count = 0; stack->head = NULL; return stack; } /* Check empty stack*/ -int Stack_empty(T stack) { +int Stack_empty(T stack) +{ assert(stack); return stack->count == 0; } /* Return size of the stack */ -int Stack_size(T stack) { +int Stack_size(T stack) +{ assert(stack); return stack->count; } /* Push an element into the stack */ -void Stack_push(T stack, void *val) { +void Stack_push(T stack, void *val) +{ elem_t *t; assert(stack); - t = (elem_t *) malloc(sizeof(elem_t)); + t = (elem_t *)malloc(sizeof(elem_t)); t->val = val; t->next = stack->head; stack->head = t; @@ -50,7 +56,8 @@ void Stack_push(T stack, void *val) { } /* Pop an element out of the stack */ -void *Stack_pop(T stack) { +void *Stack_pop(T stack) +{ void *val; elem_t *t; @@ -65,13 +72,15 @@ void *Stack_pop(T stack) { } /* Print all elements in the stack */ -void Stack_print(Stack_T stack) { +void Stack_print(Stack_T stack) +{ assert(stack); int i, size = Stack_size(stack); elem_t *current_elem = stack->head; printf("Stack [Top --- Bottom]: "); - for(i = 0; i < size; ++i) { + for (i = 0; i < size; ++i) + { printf("%p ", (int *)current_elem->val); current_elem = current_elem->next; } diff --git a/data_structures/stack/stack_linked_list/stack.h b/data_structures/stack/stack_linked_list/stack.h index ba82ed21..d9b0315e 100644 --- a/data_structures/stack/stack_linked_list/stack.h +++ b/data_structures/stack/stack_linked_list/stack.h @@ -4,12 +4,12 @@ #define T Stack_T typedef struct T *T; -extern T Stack_init (void); -extern int Stack_size (T stack); -extern int Stack_empty (T stack); -extern void Stack_push (T stack, void *val); -extern void *Stack_pop (T stack); -extern void Stack_print (T stack); +extern T Stack_init(void); +extern int Stack_size(T stack); +extern int Stack_empty(T stack); +extern void Stack_push(T stack, void *val); +extern void *Stack_pop(T stack); +extern void Stack_print(T stack); #undef T #endif diff --git a/data_structures/trie/trie.c b/data_structures/trie/trie.c index d748a11c..787ee1f5 100644 --- a/data_structures/trie/trie.c +++ b/data_structures/trie/trie.c @@ -3,8 +3,8 @@ /*-----character - 97 used for get the character from the ASCII value-----*/ -#include #include +#include #include #include @@ -16,113 +16,115 @@ typedef struct TrieNode struct TrieNode *children[ALPHABET_SIZE]; char character; bool isEndOfWord; - + } TrieNode; /*--Create new node--*/ -TrieNode *createTrieNode() -{ - TrieNode *node; +TrieNode *createTrieNode() +{ + TrieNode *node; node = malloc(sizeof(TrieNode)); - node->isEndOfWord = false; + node->isEndOfWord = false; int i = 0; - while(ichildren[i] = NULL; i++; } - return node; + return node; } /*--Insert new word to Trie--*/ -void insert(TrieNode *root,char *word) +void insert(TrieNode *root, char *word) { - /*----Addition of the word done by recurcively----*/ - - //Check wheather word character pointer is NULL - if((strlen(word)-1) != 0) - { - char character = *word; - if(root->children[character-97] == NULL) - { - TrieNode *node = NULL; - node = createTrieNode(); - node->character = character; - root->children[character-97] = node; - } - word++; - insert(root->children[character-97],word); - } - else - { - root->isEndOfWord = true; - } - return; + /*----Addition of the word done by recurcively----*/ + + // Check wheather word character pointer is NULL + if ((strlen(word) - 1) != 0) + { + char character = *word; + if (root->children[character - 97] == NULL) + { + TrieNode *node = NULL; + node = createTrieNode(); + node->character = character; + root->children[character - 97] = node; + } + word++; + insert(root->children[character - 97], word); + } + else + { + root->isEndOfWord = true; + } + return; } /*--Search a word in the Trie--*/ -TrieNode *search( TrieNode *root, char *word) +TrieNode *search(TrieNode *root, char *word) { - TrieNode *temp; - while(*word != '\0') - { - char character = *word; - if(root->children[character - 97] != NULL) - { - temp = root->children[character-97]; - word++; - root = temp; - } - else - { - printf("No possible words!!\n"); - return NULL; - } - } - return root; + TrieNode *temp; + while (*word != '\0') + { + char character = *word; + if (root->children[character - 97] != NULL) + { + temp = root->children[character - 97]; + word++; + root = temp; + } + else + { + printf("No possible words!!\n"); + return NULL; + } + } + return root; } /*---Print a word in the array--*/ -void printArray(char chars[], int len) +void printArray(char chars[], int len) { - int i; - for (i=0; icharacter; - filledLen++; + prefix[filledLen] = node->character; + filledLen++; - if (node->isEndOfWord) - { - printArray(prefix, filledLen); - } + if (node->isEndOfWord) + { + printArray(prefix, filledLen); + } - int i ; - for(i=0;ichildren[i], prefix, filledLen); - } + int i; + for (i = 0; i < ALPHABET_SIZE; i++) + { + printPathsRecur(node->children[i], prefix, filledLen); + } } /*--Travel through the Trie and return words from it--*/ -void traverse(char prefix[], TrieNode *root) +void traverse(char prefix[], TrieNode *root) { TrieNode *temp = NULL; - temp = search(root,prefix); - int j=0; - while(prefix[j]!='\0') + temp = search(root, prefix); + int j = 0; + while (prefix[j] != '\0') { j++; } - printPathsRecur(temp,prefix,j-1); + printPathsRecur(temp, prefix, j - 1); } /*------Demonstrate purposes uses text file called dictionary -------*/ @@ -137,48 +139,49 @@ char *receiveInput(char *s) return s; } -int main() +int main() { - //Read the file dictionary + // Read the file dictionary int word_count = 0; - char* words[NUMBER_OF_WORDS]; + char *words[NUMBER_OF_WORDS]; FILE *fp = fopen("dictionary.txt", "r"); - + if (fp == 0) { fprintf(stderr, "Error while opening dictionary file"); exit(1); } - + words[word_count] = malloc(INPUT_WORD_SIZE); - - while (fgets(words[word_count], INPUT_WORD_SIZE, fp)) + + while (fgets(words[word_count], INPUT_WORD_SIZE, fp)) { word_count++; words[word_count] = malloc(INPUT_WORD_SIZE); } - - //Push the words in to Trie + // Push the words in to Trie TrieNode *root = NULL; root = createTrieNode(); int i; - for(i=0;i -#include #include +#include +#include char *abbreviate(const char *phrase) { @@ -19,8 +19,8 @@ char *abbreviate(const char *phrase) /* for -loop variable */ int i = 0; - /* - counts the empty-characters. + /* + counts the empty-characters. for determine the number of words */ while (p_str && (i < 80)) @@ -43,7 +43,7 @@ char *abbreviate(const char *phrase) /* initalizes words-array with empty strings */ for (i = 0; i < counter; i++) { - strcpy(words[i],""); + strcpy(words[i], ""); } /* rewind string */ diff --git a/exercism/hello_world/hello_world.c b/exercism/hello_world/hello_world.c index 74aaa5cb..270911da 100644 --- a/exercism/hello_world/hello_world.c +++ b/exercism/hello_world/hello_world.c @@ -4,7 +4,7 @@ const char *hello(void) { - char * ans = strdup("Hello, World!"); + char *ans = strdup("Hello, World!"); /* string is pointer of the first character */ - return ans; + return ans; } diff --git a/exercism/isogram/isogram.c b/exercism/isogram/isogram.c index a54e3c81..d24f0bc7 100644 --- a/exercism/isogram/isogram.c +++ b/exercism/isogram/isogram.c @@ -4,7 +4,7 @@ /* is_isogram: returns true if the given string a isogram, otherwise false. */ -bool is_isogram(const char phrase[]) +bool is_isogram(const char phrase[]) { /* use 'unsigned' because of the function strlen(...) */ @@ -20,18 +20,18 @@ bool is_isogram(const char phrase[]) /* contains the length of the given string */ unsigned int len_phrase = strlen(phrase); - for (i = 0; i < len_phrase; i++ ) + for (i = 0; i < len_phrase; i++) { current_char = phrase[i]; /* makes sure the current character has no repetition */ - for (j = i+1; j < len_phrase; j++) + for (j = i + 1; j < len_phrase; j++) { if (current_char == phrase[j]) { status = false; - /* + /* because the given string is none isogram. that means we can exit the nested for-loop. */ @@ -40,7 +40,7 @@ bool is_isogram(const char phrase[]) } } - /* exit label */ - end: - return status; +/* exit label */ +end: + return status; } \ No newline at end of file diff --git a/exercism/rna_transcription/rna_transcription.h b/exercism/rna_transcription/rna_transcription.h index 6c3bc0f1..cab57735 100644 --- a/exercism/rna_transcription/rna_transcription.h +++ b/exercism/rna_transcription/rna_transcription.h @@ -2,6 +2,6 @@ #define __RNA_TRANSCRIPTION__H /* to_rna: compiles a DNA strand in its RNA complement */ -char * to_rna(const char s[]); +char *to_rna(const char s[]); #endif \ No newline at end of file diff --git a/exercism/word_count/word_count.c b/exercism/word_count/word_count.c index 4bdf27f5..669fa88b 100644 --- a/exercism/word_count/word_count.c +++ b/exercism/word_count/word_count.c @@ -2,7 +2,7 @@ #include /* - word_count: returns the full number of words in the input_text, + word_count: returns the full number of words in the input_text, otherwise an error code: (see below) error codes: EXCESSIVE_LENGTH_WORD -1 @@ -80,7 +80,7 @@ int word_count(const char *input_text, word_count_word_t *words) for (i = 0; i <= index_list; i++) { - if (strcmp(word_list[i],words->text) == 0) + if (strcmp(word_list[i], words->text) == 0) { words->count++; } diff --git a/exercism/word_count/word_count.h b/exercism/word_count/word_count.h index ba819414..c06f19b9 100644 --- a/exercism/word_count/word_count.h +++ b/exercism/word_count/word_count.h @@ -1,20 +1,21 @@ #ifndef WORD_COUNT_H #define WORD_COUNT_H -#define MAX_WORDS 20 // at most MAX_WORDS can be found in the test input string -#define MAX_WORD_LENGTH 50 // no individual word can exceed this length +#define MAX_WORDS 20 // at most MAX_WORDS can be found in the test input string +#define MAX_WORD_LENGTH 50 // no individual word can exceed this length // results structure -typedef struct word_count_word { - char text[MAX_WORD_LENGTH]; - int count; +typedef struct word_count_word +{ + char text[MAX_WORD_LENGTH]; + int count; } word_count_word_t; -#define EXCESSIVE_LENGTH_WORD -1 +#define EXCESSIVE_LENGTH_WORD -1 #define EXCESSIVE_NUMBER_OF_WORDS -2 -// word_count - routine to classify the unique words and their frequency in a test input string -// inputs: +// word_count - routine to classify the unique words and their frequency in a +// test input string inputs: // input_text = a null-terminated string containing that is analyzed // // outputs: @@ -22,6 +23,6 @@ typedef struct word_count_word { // uniqueWords - number of words in the words structure // returns a negative number if an error. // words will contain the results up to that point. -int word_count(const char *input_text, word_count_word_t * words); +int word_count(const char *input_text, word_count_word_t *words); #endif diff --git a/greedy_approach/djikstra.c b/greedy_approach/djikstra.c index 39f44258..fb8c6571 100644 --- a/greedy_approach/djikstra.c +++ b/greedy_approach/djikstra.c @@ -12,68 +12,77 @@ int dist[MAX]; int q[MAX]; int qp = 0; -void enqueue (int v) { - q[qp++] = v; +void enqueue(int v) { q[qp++] = v; } + +int cf(void *a, void *b) +{ + int *x = (int *)a; + int *y = (int *)b; + return *y - *x; } -int cf (void *a, void *b) { - int *x = (int *)a; - int *y = (int *)b; - return *y - *x; +int dequeue() +{ + qsort(q, qp, sizeof(int), cf); + return q[--qp]; } -int dequeue () { - qsort(q, qp, sizeof(int), cf); - return q[--qp]; -} - -int queue_has_something () { - return (qp > 0); -} +int queue_has_something() { return (qp > 0); } int visited[MAX]; int vp = 0; -void dijkstra (int s) { - dist[s] = 0; - int i; - for (i = 0; i < V; ++i) { - if (i != s) { - dist[i] = INF; - } - enqueue(i); - } - while (queue_has_something()) { - int u = dequeue(); - visited[vp++] = u; - for (i = 0; i < V; ++i) { - if (mat[u][i]) { - if (dist[i] > dist[u] + mat[u][i]) { - dist[i] = dist[u] + mat[u][i]; - } - } - } - } +void dijkstra(int s) +{ + dist[s] = 0; + int i; + for (i = 0; i < V; ++i) + { + if (i != s) + { + dist[i] = INF; + } + enqueue(i); + } + while (queue_has_something()) + { + int u = dequeue(); + visited[vp++] = u; + for (i = 0; i < V; ++i) + { + if (mat[u][i]) + { + if (dist[i] > dist[u] + mat[u][i]) + { + dist[i] = dist[u] + mat[u][i]; + } + } + } + } } -int main(int argc, char const *argv[]) { +int main(int argc, char const *argv[]) +{ - printf("Enter the number of vertices: "); - scanf(" %d", &V); - printf("Enter the adj matrix: "); - int i, j; - for (i = 0; i < V; ++i) { - for (j = 0; j < V; ++j) { - scanf(" %d", &mat[i][j]); - } - } - - dijkstra(0); + printf("Enter the number of vertices: "); + scanf(" %d", &V); + printf("Enter the adj matrix: "); + int i, j; + for (i = 0; i < V; ++i) + { + for (j = 0; j < V; ++j) + { + scanf(" %d", &mat[i][j]); + } + } - printf("\nNode\tDist\n"); - for (i = 0; i < V; ++i) { - printf("%d\t%d\n", i, dist[i]); - } - - return 0; + dijkstra(0); + + printf("\nNode\tDist\n"); + for (i = 0; i < V; ++i) + { + printf("%d\t%d\n", i, dist[i]); + } + + return 0; } diff --git a/hash/hash.c b/hash/hash.c index b8a4b37f..f5eb3fbf 100644 --- a/hash/hash.c +++ b/hash/hash.c @@ -65,14 +65,16 @@ int adler_32(char s[]) /* crc32 Hash-Algorithm*/ #include -uint32_t crc32(char* data){ +uint32_t crc32(char *data) +{ int i = 0; uint32_t crc = 0xffffffff; - while(data[i] != '\0'){ + while (data[i] != '\0') + { uint8_t byte = data[i]; crc = crc ^ byte; - for(int j = 8; j > 0; --j) - crc = (crc >> 1) ^ (0xEDB88320 & ( -(crc & 1))); + for (int j = 8; j > 0; --j) + crc = (crc >> 1) ^ (0xEDB88320 & (-(crc & 1))); i++; } diff --git a/hash/hash.h b/hash/hash.h index 8d2e8091..3804fca8 100644 --- a/hash/hash.h +++ b/hash/hash.h @@ -46,6 +46,4 @@ int adler_32(char[]); */ int crc32(char[]); - - #endif \ No newline at end of file diff --git a/hash/test_program.c b/hash/test_program.c index 1ce85c85..604ad89f 100644 --- a/hash/test_program.c +++ b/hash/test_program.c @@ -3,8 +3,8 @@ This file contains a simple test program for each hash-function. */ -#include #include "hash.h" +#include int main(void) { @@ -13,7 +13,7 @@ int main(void) /* actual tests */ printf("sdbm: %s --> %llX\n", s, sdbm(s)); printf("djb2: %s --> %llX\n", s, djb2(s)); - printf("xor8: %s --> %X\n", s, xor8(s)); /* 8 bit */ + printf("xor8: %s --> %X\n", s, xor8(s)); /* 8 bit */ printf("adler_32: %s --> %X\n", s, adler_32(s)); /* 32 bit */ return 0; diff --git a/leetcode/src/1.c b/leetcode/src/1.c index f30abbe7..53f260a1 100644 --- a/leetcode/src/1.c +++ b/leetcode/src/1.c @@ -1,10 +1,13 @@ -int* twoSum(int* nums, int numsSize, int target, int* returnSize){ +int *twoSum(int *nums, int numsSize, int target, int *returnSize) +{ int i, j; int *ret = calloc(2, sizeof(int)); - for (i = 0; i < numsSize; i++) { + for (i = 0; i < numsSize; i++) + { int key = target - nums[i]; for (j = i + 1; j < numsSize; j++) - if (nums[j] == key) { + if (nums[j] == key) + { ret[0] = i; ret[1] = j; } diff --git a/leetcode/src/101.c b/leetcode/src/101.c index d1c03603..68a8dc5e 100644 --- a/leetcode/src/101.c +++ b/leetcode/src/101.c @@ -7,14 +7,17 @@ * }; */ -bool checkSymmetric(struct TreeNode *left, struct TreeNode *right) { +bool checkSymmetric(struct TreeNode *left, struct TreeNode *right) +{ if (!left || !right) return left == right; if (left->val != right->val) return 0; - return checkSymmetric(left->left, right->right) && checkSymmetric(left->right, right->left); + return checkSymmetric(left->left, right->right) && + checkSymmetric(left->right, right->left); } -bool isSymmetric(struct TreeNode* root){ +bool isSymmetric(struct TreeNode *root) +{ return root == NULL || checkSymmetric(root->left, root->right); } diff --git a/leetcode/src/104.c b/leetcode/src/104.c index 6326512a..91d8019a 100644 --- a/leetcode/src/104.c +++ b/leetcode/src/104.c @@ -7,16 +7,17 @@ * }; */ -int maxval(int a, int b) { +int maxval(int a, int b) +{ if (a > b) return a; else return b; } -int maxDepth(struct TreeNode* root){ +int maxDepth(struct TreeNode *root) +{ if (root == NULL) return 0; else return 1 + maxval(maxDepth(root->left), maxDepth(root->right)); } - diff --git a/leetcode/src/108.c b/leetcode/src/108.c index 37d3e95e..24ab5498 100644 --- a/leetcode/src/108.c +++ b/leetcode/src/108.c @@ -7,10 +7,12 @@ * }; */ -struct TreeNode* convertBST(int *nums, int left, int right) { +struct TreeNode *convertBST(int *nums, int left, int right) +{ if (left > right) return NULL; - else { + else + { int mid = (right + left) / 2; struct TreeNode *new_val = malloc(sizeof(struct TreeNode)); new_val->val = nums[mid]; @@ -20,10 +22,10 @@ struct TreeNode* convertBST(int *nums, int left, int right) { } } -struct TreeNode* sortedArrayToBST(int* nums, int numsSize){ - if(numsSize == 0) +struct TreeNode *sortedArrayToBST(int *nums, int numsSize) +{ + if (numsSize == 0) return NULL; else - return convertBST(nums, 0, numsSize -1); + return convertBST(nums, 0, numsSize - 1); } - diff --git a/leetcode/src/1089.c b/leetcode/src/1089.c index df1cfbb7..81c89b8c 100644 --- a/leetcode/src/1089.c +++ b/leetcode/src/1089.c @@ -1,14 +1,18 @@ -void duplicateZeros(int* arr, int arrSize){ +void duplicateZeros(int *arr, int arrSize) +{ int i, start = 0; int *tmp = malloc(arrSize * sizeof(int)); /* Copy arr into tmp arr */ - for(i = 0; i < arrSize; i++) { + for (i = 0; i < arrSize; i++) + { tmp[i] = arr[i]; } i = 0; - for(start = 0; start < arrSize; start++) { + for (start = 0; start < arrSize; start++) + { arr[start] = tmp[i]; - if(tmp[i] == 0) { + if (tmp[i] == 0) + { start++; if (start < arrSize) arr[start] = 0; @@ -16,5 +20,3 @@ void duplicateZeros(int* arr, int arrSize){ i++; } } - - diff --git a/leetcode/src/109.c b/leetcode/src/109.c index caaf34c4..5daf5ac3 100644 --- a/leetcode/src/109.c +++ b/leetcode/src/109.c @@ -1,21 +1,23 @@ -struct TreeNode* buildBST(struct ListNode* head, struct ListNode* tail) { - if(head == tail) +struct TreeNode *buildBST(struct ListNode *head, struct ListNode *tail) +{ + if (head == tail) return NULL; - struct ListNode* slow = head, *fast = head; - while(fast != tail && fast->next != tail) { + struct ListNode *slow = head, *fast = head; + while (fast != tail && fast->next != tail) + { fast = fast->next->next; slow = slow->next; } - struct TreeNode* node = malloc(sizeof(struct TreeNode)); + struct TreeNode *node = malloc(sizeof(struct TreeNode)); node->val = slow->val; node->left = buildBST(head, slow); node->right = buildBST(slow->next, tail); return node; } -struct TreeNode* sortedListToBST(struct ListNode* head){ +struct TreeNode *sortedListToBST(struct ListNode *head) +{ if (!head) return NULL; else return buildBST(head, NULL); } - diff --git a/leetcode/src/11.c b/leetcode/src/11.c index 1530a86b..05f9d850 100644 --- a/leetcode/src/11.c +++ b/leetcode/src/11.c @@ -1,30 +1,28 @@ -//Fucntion to calculate min of values a and b -int min(int a, int b){ - return ((ares) + while (start < end) + { + // Calculate current area by taking minimum of two heights + int currArea = (end - start) * min(height[start], height[end]); + + if (currArea > res) res = currArea; - if(height[start]= b ? a : b; -} +int max(int a, int b) { return a >= b ? a : b; } -int height(struct TreeNode* root) { +int height(struct TreeNode *root) +{ if (root == NULL) return 0; else return 1 + max(height(root->left), height(root->right)); } -bool isBalanced(struct TreeNode* root){ +bool isBalanced(struct TreeNode *root) +{ if (root == NULL) return 1; int left = height(root->left); int right = height(root->right); - return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right); + return abs(left - right) <= 1 && isBalanced(root->left) && + isBalanced(root->right); } - diff --git a/leetcode/src/112.c b/leetcode/src/112.c index d71bea45..dc3256d9 100644 --- a/leetcode/src/112.c +++ b/leetcode/src/112.c @@ -1,7 +1,9 @@ -bool hasPathSum(struct TreeNode* root, int sum) { +bool hasPathSum(struct TreeNode *root, int sum) +{ if (root == NULL) return 0; if (!root->left && !root->right && sum - root->val == 0) return 1; - return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); + return hasPathSum(root->left, sum - root->val) || + hasPathSum(root->right, sum - root->val); } diff --git a/leetcode/src/1184.c b/leetcode/src/1184.c index 50aef4a4..56ea3d0a 100644 --- a/leetcode/src/1184.c +++ b/leetcode/src/1184.c @@ -1,16 +1,20 @@ -int distanceBetweenBusStops(int* distance, int distanceSize, int start, int destination){ +int distanceBetweenBusStops(int *distance, int distanceSize, int start, + int destination) +{ - int sum1 = 0, sum2 = 0; - if (start > destination) { - int tmp = start; - start = destination; - destination = tmp; - } - for (auto i = 0; i < distanceSize; ++i) { - if (i >= start && i < destination) - sum1 += distance[i]; - else - sum2 += distance[i]; - } - return sum1 < sum2 ? sum1 : sum2; + int sum1 = 0, sum2 = 0; + if (start > destination) + { + int tmp = start; + start = destination; + destination = tmp; + } + for (auto i = 0; i < distanceSize; ++i) + { + if (i >= start && i < destination) + sum1 += distance[i]; + else + sum2 += distance[i]; + } + return sum1 < sum2 ? sum1 : sum2; } diff --git a/leetcode/src/1189.c b/leetcode/src/1189.c index 030ba243..c1af4453 100644 --- a/leetcode/src/1189.c +++ b/leetcode/src/1189.c @@ -1,6 +1,7 @@ -int maxNumberOfBalloons(char * text){ - /* - 0 -> b, +int maxNumberOfBalloons(char *text) +{ + /* + 0 -> b, 1 -> a, 2 -> l, 3 -> o, @@ -8,31 +9,43 @@ int maxNumberOfBalloons(char * text){ */ int count_letters[5] = {0}; int i, min_counter_ballons; - - for (char *ptr = text; *ptr; ptr++) { - if (*ptr == 'b') { + + for (char *ptr = text; *ptr; ptr++) + { + if (*ptr == 'b') + { count_letters[0]++; - } else if(*ptr == 'a') { + } + else if (*ptr == 'a') + { count_letters[1]++; - } else if (*ptr == 'l') { + } + else if (*ptr == 'l') + { count_letters[2]++; - } else if(*ptr == 'o') { + } + else if (*ptr == 'o') + { count_letters[3]++; - } else if(*ptr == 'n') { + } + else if (*ptr == 'n') + { count_letters[4]++; } } - + /* Divide by 2 the repeted letters */ count_letters[2] /= 2; count_letters[3] /= 2; - - /* Max number of times which we can write ballon is equal to min value of letters on count_letter */ + + /* Max number of times which we can write ballon is equal to min value of + * letters on count_letter */ min_counter_ballons = count_letters[0]; - for (i = 1; i < 5; i++) { + for (i = 1; i < 5; i++) + { if (count_letters[i] < min_counter_ballons) min_counter_ballons = count_letters[i]; } - + return min_counter_ballons; } diff --git a/leetcode/src/12.c b/leetcode/src/12.c index ec33b979..b8d8f7c0 100644 --- a/leetcode/src/12.c +++ b/leetcode/src/12.c @@ -1,164 +1,172 @@ -char *getOne(char c){ - switch (c) { - case '9': - return "IX"; +char *getOne(char c) +{ + switch (c) + { + case '9': + return "IX"; - case '8': - return "VIII"; + case '8': + return "VIII"; - case '7': - return "VII"; + case '7': + return "VII"; - case '6': - return "VI"; + case '6': + return "VI"; - case '5': - return "V"; + case '5': + return "V"; - case '4': - return "IV"; + case '4': + return "IV"; - case '3': - return "III"; + case '3': + return "III"; - case '2': - return "II"; + case '2': + return "II"; - case '1': - return "I"; + case '1': + return "I"; - case '0': - return ""; + case '0': + return ""; - default: - return NULL; + default: + return NULL; } } -char *getTen(char c){ - switch (c) { - case '9': - return "XC"; +char *getTen(char c) +{ + switch (c) + { + case '9': + return "XC"; - case '8': - return "LXXX"; + case '8': + return "LXXX"; - case '7': - return "LXX"; + case '7': + return "LXX"; - case '6': - return "LX"; + case '6': + return "LX"; - case '5': - return "L"; + case '5': + return "L"; - case '4': - return "XL"; + case '4': + return "XL"; - case '3': - return "XXX"; + case '3': + return "XXX"; - case '2': - return "XX"; + case '2': + return "XX"; - case '1': - return "X"; + case '1': + return "X"; - case '0': - return ""; + case '0': + return ""; - default: - return NULL; - } - -} - -char *getHundred(char c){ - switch (c) { - case '9': - return "CM"; - - case '8': - return "DCCC"; - - case '7': - return "DCC"; - - case '6': - return "DC"; - - case '5': - return "D"; - - case '4': - return "CD"; - - case '3': - return "CCC"; - - case '2': - return "CC"; - - case '1': - return "C"; - - case '0': - return ""; - - default: - return NULL; + default: + return NULL; } } -char *getThousand(char c){ - switch (c) { - case '3': - return "MMM"; +char *getHundred(char c) +{ + switch (c) + { + case '9': + return "CM"; - case '2': - return "MM"; + case '8': + return "DCCC"; - case '1': - return "M"; - - default: - return NULL; + case '7': + return "DCC"; + + case '6': + return "DC"; + + case '5': + return "D"; + + case '4': + return "CD"; + + case '3': + return "CCC"; + + case '2': + return "CC"; + + case '1': + return "C"; + + case '0': + return ""; + + default: + return NULL; } } +char *getThousand(char c) +{ + switch (c) + { + case '3': + return "MMM"; + case '2': + return "MM"; + case '1': + return "M"; -char * intToRoman(int num){ + default: + return NULL; + } +} + +char *intToRoman(int num) +{ int length; char number[5]; - char *s = malloc(16*sizeof(char)); - - sprintf(number, "%i", num); - + char *s = malloc(16 * sizeof(char)); + + sprintf(number, "%i", num); + length = strlen(number); - switch (length){ - case 4: - sprintf(s,"%s%s%s%s", getThousand(number[0]), getHundred(number[1]), getTen(number[2]), getOne(number[3])); - break; + switch (length) + { + case 4: + sprintf(s, "%s%s%s%s", getThousand(number[0]), getHundred(number[1]), + getTen(number[2]), getOne(number[3])); + break; - case 3: - sprintf(s,"%s%s%s", getHundred(number[0]), getTen(number[1]), getOne(number[2])); - - break; + case 3: + sprintf(s, "%s%s%s", getHundred(number[0]), getTen(number[1]), + getOne(number[2])); - case 2: - sprintf(s,"%s%s", getTen(number[0]), getOne(number[1])); - - break; + break; - case 1: - s = getOne(number[0]); - break; + case 2: + sprintf(s, "%s%s", getTen(number[0]), getOne(number[1])); - default: - break; + break; + + case 1: + s = getOne(number[0]); + break; + + default: + break; } return s; } diff --git a/leetcode/src/1207.c b/leetcode/src/1207.c index e8e830b0..8c8eb8dc 100644 --- a/leetcode/src/1207.c +++ b/leetcode/src/1207.c @@ -1,14 +1,14 @@ #define MAP_SIZE 2048 -int cmpvalue(const void *a, const void *b) { - return *(int *)b - *(int *)a; -} -bool uniqueOccurrences(int* arr, int arrSize){ +int cmpvalue(const void *a, const void *b) { return *(int *)b - *(int *)a; } +bool uniqueOccurrences(int *arr, int arrSize) +{ int *map = calloc(MAP_SIZE, sizeof(int)); int i; - for(i = 0; i < arrSize; i++) { + for (i = 0; i < arrSize; i++) + { if (arr[i] < 0) - map[arr[i] + MAP_SIZE/2] += 1; + map[arr[i] + MAP_SIZE / 2] += 1; else map[arr[i]] += 1; } @@ -16,8 +16,9 @@ bool uniqueOccurrences(int* arr, int arrSize){ Ex: 3 2 1 0 0 0 0 */ qsort(map, MAP_SIZE, sizeof(int), cmpvalue); i = 0; - while(map[i]) { - if(map[i] == map[i+1]) + while (map[i]) + { + if (map[i] == map[i + 1]) return 0; i++; } diff --git a/leetcode/src/121.c b/leetcode/src/121.c index 2741ce99..43d3b6a7 100644 --- a/leetcode/src/121.c +++ b/leetcode/src/121.c @@ -1,17 +1,17 @@ -int maxcmp(int a, int b) { - return (a >= b)? a : b; -} +int maxcmp(int a, int b) { return (a >= b) ? a : b; } /* max subarray problem by using Kadane's Algorithm */ -int maxProfit(int* prices, int pricesSize){ - /* maxCur: current maximum - * maxSoFar: found maximum for subarray so far - */ - int maxCur = 0, maxSoFar = 0; - for(int i = 1; i < pricesSize; i++) { - maxCur = maxcmp(0, maxCur + prices[i] - prices[i - 1]); - maxSoFar = maxcmp(maxSoFar, maxCur); - } - return maxSoFar; +int maxProfit(int *prices, int pricesSize) +{ + /* maxCur: current maximum + * maxSoFar: found maximum for subarray so far + */ + int maxCur = 0, maxSoFar = 0; + for (int i = 1; i < pricesSize; i++) + { + maxCur = maxcmp(0, maxCur + prices[i] - prices[i - 1]); + maxSoFar = maxcmp(maxSoFar, maxCur); + } + return maxSoFar; } diff --git a/leetcode/src/125.c b/leetcode/src/125.c index 3df697c4..07a210b0 100644 --- a/leetcode/src/125.c +++ b/leetcode/src/125.c @@ -1,15 +1,21 @@ -bool isPalindrome(char * s){ +bool isPalindrome(char *s) +{ int start = 0, end = strlen(s) - 1; - while(start < end) { - if (!isalpha(s[start]) && !isalnum(s[start])) { + while (start < end) + { + if (!isalpha(s[start]) && !isalnum(s[start])) + { start++; } - else if (!isalpha(s[end]) && !isalnum(s[end])) { + else if (!isalpha(s[end]) && !isalnum(s[end])) + { end--; - } else { + } + else + { char c1 = tolower(s[start]); char c2 = tolower(s[end]); - if(c1 != c2) + if (c1 != c2) return 0; start++; end--; diff --git a/leetcode/src/13.c b/leetcode/src/13.c index 0da82cf9..1450813b 100644 --- a/leetcode/src/13.c +++ b/leetcode/src/13.c @@ -1,48 +1,57 @@ -int romanToInt(char * s){ +int romanToInt(char *s) +{ int romanToInt = 0; - for (int i = 0; i < strlen(s); i++) { - switch(s[i]) { - case 'I': - if (i+1 < strlen(s)) { - if (s[i + 1] == 'V' || s[i + 1] == 'X') { - romanToInt -= 1; - break; - } + for (int i = 0; i < strlen(s); i++) + { + switch (s[i]) + { + case 'I': + if (i + 1 < strlen(s)) + { + if (s[i + 1] == 'V' || s[i + 1] == 'X') + { + romanToInt -= 1; + break; } - romanToInt += 1; - break; - case 'V': - romanToInt += 5; - break; - case 'X': - if (i+1 < strlen(s)) { - if (s[i + 1] == 'L' || s[i + 1] == 'C') { - romanToInt -= 10; - break; - } + } + romanToInt += 1; + break; + case 'V': + romanToInt += 5; + break; + case 'X': + if (i + 1 < strlen(s)) + { + if (s[i + 1] == 'L' || s[i + 1] == 'C') + { + romanToInt -= 10; + break; } - romanToInt += 10; - break; - case 'L': - romanToInt += 50; - break; - case 'C': - if (i+1 < strlen(s)) { - if (s[i + 1] == 'D' || s[i + 1] == 'M') { - romanToInt -= 100; - break; - } + } + romanToInt += 10; + break; + case 'L': + romanToInt += 50; + break; + case 'C': + if (i + 1 < strlen(s)) + { + if (s[i + 1] == 'D' || s[i + 1] == 'M') + { + romanToInt -= 100; + break; } - romanToInt += 100; - break; - case 'D': - romanToInt += 500; - break; - case 'M': - romanToInt += 1000; - break; - default: - break; + } + romanToInt += 100; + break; + case 'D': + romanToInt += 500; + break; + case 'M': + romanToInt += 1000; + break; + default: + break; } } return romanToInt; diff --git a/leetcode/src/136.c b/leetcode/src/136.c index 4d597e98..bdbab6b9 100644 --- a/leetcode/src/136.c +++ b/leetcode/src/136.c @@ -1,6 +1,7 @@ -int singleNumber(int* nums, int numsSize){ +int singleNumber(int *nums, int numsSize) +{ int i, result = 0; - for(i = 0; i < numsSize; i++) + for (i = 0; i < numsSize; i++) result = result ^ nums[i]; return result; } diff --git a/leetcode/src/141.c b/leetcode/src/141.c index f418a116..6e4ac65a 100644 --- a/leetcode/src/141.c +++ b/leetcode/src/141.c @@ -5,12 +5,15 @@ * struct ListNode *next; * }; */ -bool hasCycle(struct ListNode *head) { - struct ListNode *fast=head, *slow=head; - while( slow && fast && fast->next ){ - fast=fast->next->next; - slow=slow->next; - if(fast==slow) return true; +bool hasCycle(struct ListNode *head) +{ + struct ListNode *fast = head, *slow = head; + while (slow && fast && fast->next) + { + fast = fast->next->next; + slow = slow->next; + if (fast == slow) + return true; } return false; } diff --git a/leetcode/src/142.c b/leetcode/src/142.c index 46805d06..c45fe586 100644 --- a/leetcode/src/142.c +++ b/leetcode/src/142.c @@ -1,16 +1,20 @@ -struct ListNode *detectCycle(struct ListNode *head) { +struct ListNode *detectCycle(struct ListNode *head) +{ if (head == NULL || head->next == NULL) return NULL; struct ListNode *slow, *fast; slow = fast = head; - while(fast && fast->next) { + while (fast && fast->next) + { slow = slow->next; fast = fast->next->next; - if(slow == fast) { + if (slow == fast) + { struct ListNode *entry = head; - while(slow != entry) { - slow = slow -> next; - entry = entry -> next; + while (slow != entry) + { + slow = slow->next; + entry = entry->next; } return entry; } diff --git a/leetcode/src/153.c b/leetcode/src/153.c index 2a86a4b5..84b8a12a 100644 --- a/leetcode/src/153.c +++ b/leetcode/src/153.c @@ -1,7 +1,9 @@ -int findMin(int* nums, int numsSize){ +int findMin(int *nums, int numsSize) +{ int low = 0, high = numsSize - 1; - while (low < high) { - int mid = low + (high - low) / 2; + while (low < high) + { + int mid = low + (high - low) / 2; /* minimum is on left side */ if (nums[mid] < nums[high]) high = mid; diff --git a/leetcode/src/160.c b/leetcode/src/160.c index fccd21ec..bfca759b 100644 --- a/leetcode/src/160.c +++ b/leetcode/src/160.c @@ -1,17 +1,19 @@ -struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) { +struct ListNode *getIntersectionNode(struct ListNode *headA, + struct ListNode *headB) +{ struct ListNode *cur1 = headA, *cur2 = headB; - if(cur1 == NULL || cur2 == NULL) + if (cur1 == NULL || cur2 == NULL) return NULL; - while (cur1 && cur2 && cur1 != cur2) { - cur1 = cur1 -> next; - cur2 = cur2 -> next; + while (cur1 && cur2 && cur1 != cur2) + { + cur1 = cur1->next; + cur2 = cur2->next; if (cur1 == cur2) return cur1; - if(!cur1) + if (!cur1) cur1 = headB; - if(!cur2) + if (!cur2) cur2 = headA; } return cur1; - } diff --git a/leetcode/src/169.c b/leetcode/src/169.c index 62501e11..6a2215be 100644 --- a/leetcode/src/169.c +++ b/leetcode/src/169.c @@ -1,13 +1,17 @@ /* Boyer-Moore Majority Vote Algorithm * http://www.cs.utexas.edu/~moore/best-ideas/mjrty/ */ -int majorityElement(int* nums, int numsSize){ +int majorityElement(int *nums, int numsSize) +{ int count = 1; int majorNum = nums[0]; - for (int i = 1; i < numsSize; i++) { - if(count == 0) { + for (int i = 1; i < numsSize; i++) + { + if (count == 0) + { majorNum = nums[i]; count++; - } else if (majorNum == nums[i]) + } + else if (majorNum == nums[i]) count++; else count--; diff --git a/leetcode/src/173.c b/leetcode/src/173.c index 018ea3eb..0dcc5996 100644 --- a/leetcode/src/173.c +++ b/leetcode/src/173.c @@ -9,37 +9,41 @@ #include -typedef struct { +typedef struct +{ int *values; int CurrentIndex; int NumberOfNodes; } BSTIterator; -void TraverseAndAssign(struct TreeNode *root, BSTIterator *obj) { - if(!root) +void TraverseAndAssign(struct TreeNode *root, BSTIterator *obj) +{ + if (!root) return; - if(root->left) + if (root->left) TraverseAndAssign(root->left, obj); obj->values[obj->CurrentIndex] = root->val; obj->CurrentIndex++; - if(root->right) + if (root->right) TraverseAndAssign(root->right, obj); } -int TotalNodes(struct TreeNode *root) { - if(!root) +int TotalNodes(struct TreeNode *root) +{ + if (!root) return 0; int nodes_left = TotalNodes(root->left); int nodes_right = TotalNodes(root->right); return nodes_left + nodes_right + 1; } -BSTIterator* bSTIteratorCreate(struct TreeNode* root) { +BSTIterator *bSTIteratorCreate(struct TreeNode *root) +{ int n = TotalNodes(root); - int size = n+1; + int size = n + 1; printf("%d", size); - BSTIterator *obj = (BSTIterator*)malloc(sizeof(BSTIterator)); - obj->values = (int*)calloc(size, sizeof(int)); + BSTIterator *obj = (BSTIterator *)malloc(sizeof(BSTIterator)); + obj->values = (int *)calloc(size, sizeof(int)); obj->CurrentIndex = 0; obj->NumberOfNodes = n; obj->values[size - 1] = INT_MAX; @@ -49,22 +53,26 @@ BSTIterator* bSTIteratorCreate(struct TreeNode* root) { } /** @return the next smallest number */ -int bSTIteratorNext(BSTIterator* obj) { +int bSTIteratorNext(BSTIterator *obj) +{ int NextValue = obj->values[obj->CurrentIndex]; obj->CurrentIndex++; return NextValue; } /** @return whether we have a next smallest number */ -bool bSTIteratorHasNext(BSTIterator* obj) { - if(!obj->NumberOfNodes) { +bool bSTIteratorHasNext(BSTIterator *obj) +{ + if (!obj->NumberOfNodes) + { return false; } printf(" Here "); return (obj->values[obj->CurrentIndex] == INT_MAX) ? false : true; } -void bSTIteratorFree(BSTIterator* obj) { +void bSTIteratorFree(BSTIterator *obj) +{ free(obj->values); free(obj); } diff --git a/leetcode/src/189.c b/leetcode/src/189.c index 19299328..efdb88b5 100644 --- a/leetcode/src/189.c +++ b/leetcode/src/189.c @@ -1,11 +1,14 @@ -void rotate(int* nums, int numsSize, int k){ - for(int i = 1; i <= k; i++){ - int j; - int lastElement; - lastElement = nums[numsSize - 1]; - for(j = numsSize - 1; j > 0; j--){ - nums[j] = nums[j - 1]; +void rotate(int *nums, int numsSize, int k) +{ + for (int i = 1; i <= k; i++) + { + int j; + int lastElement; + lastElement = nums[numsSize - 1]; + for (j = numsSize - 1; j > 0; j--) + { + nums[j] = nums[j - 1]; + } + nums[0] = lastElement; } - nums[0] = lastElement; - } } \ No newline at end of file diff --git a/leetcode/src/190.c b/leetcode/src/190.c index 80ab52a6..0fc3306f 100644 --- a/leetcode/src/190.c +++ b/leetcode/src/190.c @@ -1,13 +1,25 @@ -uint32_t reverseBits(uint32_t n) { +uint32_t reverseBits(uint32_t n) +{ uint TotalBits = 32; - uint32_t reverse_int = 0; //stored in memory as 32 bits, each bit valued 0 + uint32_t reverse_int = 0; // stored in memory as 32 bits, each bit valued 0 uint i; - for(i = 0; i < TotalBits; i++) { - if((n & (UINT32_C(1) << i))) //if the bit on the ith position of 32 bit input is 1, then proceed - //Further note the use of UINT32_C to convert 1 to unsigned 32 bit int, since just 1 is treated as int which cannot be shifted left more than 30 times - reverse_int = reverse_int | (UINT32_C(1) << (TotalBits - 1 - i)); //Convert the ith bit from the end in reverse_int from 0 to 1, if ith bit from beginning in n is 1 - //This is achieved by using bitwise OR on reverse_int (where ith bit from end is currently 0) and - //1 shifted left 31 - i bits (to ith bit from the end) + for (i = 0; i < TotalBits; i++) + { + if ((n & + (UINT32_C(1) + << i))) // if the bit on the ith position of 32 bit input is 1, + // then proceed Further note the use of UINT32_C to convert + // 1 to unsigned 32 bit int, since just 1 is treated as int + // which cannot be shifted left more than 30 times + reverse_int = + reverse_int | + (UINT32_C(1) + << (TotalBits - 1 - + i)); // Convert the ith bit from the end in reverse_int + // from 0 to 1, if ith bit from beginning in n is 1 + // This is achieved by using bitwise OR on reverse_int + // (where ith bit from end is currently 0) and 1 + // shifted left 31 - i bits (to ith bit from the end) } return reverse_int; } \ No newline at end of file diff --git a/leetcode/src/191.c b/leetcode/src/191.c index 6aaf2f20..b3c6c69d 100644 --- a/leetcode/src/191.c +++ b/leetcode/src/191.c @@ -1,9 +1,14 @@ -int hammingWeight(uint32_t n) { +int hammingWeight(uint32_t n) +{ int TotalBits = 32; int i, weight = 0; - for(i = 0; i < TotalBits; i++) { - if(n & (UINT32_C(1) << i)) //if the bit on the ith position of 32 bit input is 1, then proceed - //Further note the use of UINT32_C to convert 1 to unsigned 32 bit int, as just 1 is treated as int which cannot be shifted left more than 30 times + for (i = 0; i < TotalBits; i++) + { + if (n & (UINT32_C(1) + << i)) // if the bit on the ith position of 32 bit input is 1, + // then proceed Further note the use of UINT32_C to + // convert 1 to unsigned 32 bit int, as just 1 is treated + // as int which cannot be shifted left more than 30 times weight += 1; } return weight; diff --git a/leetcode/src/2.c b/leetcode/src/2.c index d929ef5b..d2bec030 100644 --- a/leetcode/src/2.c +++ b/leetcode/src/2.c @@ -6,7 +6,8 @@ * }; */ -struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { +struct ListNode *addTwoNumbers(struct ListNode *l1, struct ListNode *l2) +{ struct ListNode *head = NULL; struct ListNode *walk = NULL; struct ListNode *tmp = NULL; @@ -16,36 +17,41 @@ struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { int val2 = 0; int val = 0; - while(l1 != NULL || l2 != NULL || carry) { - val1 = 0; - val2 = 0; - val = 0; + while (l1 != NULL || l2 != NULL || carry) + { + val1 = 0; + val2 = 0; + val = 0; - if(l1) { - val1 = l1->val; - l1 = l1->next; - } - - if(l2) { - val2 = l2->val; - l2 = l2->next; - } - - val = carry + val1 + val2; - carry = val / 10; - - tmp = malloc(sizeof(struct ListNode)); - tmp->val = val % 10; - tmp->next = NULL; - - if(!head) { - head = walk = tmp; - } else { - walk->next = tmp; - walk = walk->next; - } + if (l1) + { + val1 = l1->val; + l1 = l1->next; } - return head; -} + if (l2) + { + val2 = l2->val; + l2 = l2->next; + } + val = carry + val1 + val2; + carry = val / 10; + + tmp = malloc(sizeof(struct ListNode)); + tmp->val = val % 10; + tmp->next = NULL; + + if (!head) + { + head = walk = tmp; + } + else + { + walk->next = tmp; + walk = walk->next; + } + } + + return head; +} diff --git a/leetcode/src/20.c b/leetcode/src/20.c index fec96017..7d3ad5c0 100644 --- a/leetcode/src/20.c +++ b/leetcode/src/20.c @@ -1,26 +1,29 @@ -bool isValid(char * s){ +bool isValid(char *s) +{ int i, k = 0, len = strlen(s); char *store = calloc(len, sizeof(char)); - for( i = 0; s[i] != '\0'; i++) { - switch(s[i]) { - case '(': - case '{': - case '[': - store[k++] = s[i]; - break; - case ')': - if(k < 1 || store[--k] != '(') - goto out; - break; - case '}': - if(k < 1 || store[--k] != '{') - goto out; - break; - case ']': - if(k < 1 || store[--k] != '[') - goto out; - break; + for (i = 0; s[i] != '\0'; i++) + { + switch (s[i]) + { + case '(': + case '{': + case '[': + store[k++] = s[i]; + break; + case ')': + if (k < 1 || store[--k] != '(') + goto out; + break; + case '}': + if (k < 1 || store[--k] != '{') + goto out; + break; + case ']': + if (k < 1 || store[--k] != '[') + goto out; + break; } } out: diff --git a/leetcode/src/201.c b/leetcode/src/201.c index 74a8e77c..47507f4f 100644 --- a/leetcode/src/201.c +++ b/leetcode/src/201.c @@ -1,6 +1,8 @@ -int rangeBitwiseAnd(int m, int n){ - while (m < n) { - n &= n-1; +int rangeBitwiseAnd(int m, int n) +{ + while (m < n) + { + n &= n - 1; } return n; } \ No newline at end of file diff --git a/leetcode/src/203.c b/leetcode/src/203.c index 5ae6588f..f652aaeb 100644 --- a/leetcode/src/203.c +++ b/leetcode/src/203.c @@ -1,10 +1,14 @@ -struct ListNode* removeElements(struct ListNode* head, int val){ +struct ListNode *removeElements(struct ListNode *head, int val) +{ if (head == NULL) return NULL; - if(head->val == val) { + if (head->val == val) + { return removeElements(head->next, val); - } else { - head -> next = removeElements(head->next, val); + } + else + { + head->next = removeElements(head->next, val); } return head; } diff --git a/leetcode/src/206.c b/leetcode/src/206.c index 3eae2936..adc4657b 100644 --- a/leetcode/src/206.c +++ b/leetcode/src/206.c @@ -6,13 +6,14 @@ * }; */ - -struct ListNode* reverseList(struct ListNode* head){ +struct ListNode *reverseList(struct ListNode *head) +{ struct ListNode *res = NULL; - while(head) { + while (head) + { struct ListNode *pre_node = head; - head = head -> next; - pre_node -> next = res; + head = head->next; + pre_node->next = res; res = pre_node; } return res; diff --git a/leetcode/src/21.c b/leetcode/src/21.c index 08f6f71a..54d31e1b 100644 --- a/leetcode/src/21.c +++ b/leetcode/src/21.c @@ -1,7 +1,8 @@ /* * Iterative approach */ -struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) { +struct ListNode *mergeTwoLists(struct ListNode *l1, struct ListNode *l2) +{ struct ListNode *list = NULL; struct ListNode *tmp = NULL; @@ -10,20 +11,28 @@ struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) { if (!l2) return l1; - if (l1 && l2) { - if (l1->val < l2->val) { + if (l1 && l2) + { + if (l1->val < l2->val) + { list = tmp = l1; l1 = l1->next; - } else { + } + else + { list = tmp = l2; l2 = l2->next; } - while(l1 && l2) { - if (l1->val < l2->val) { + while (l1 && l2) + { + if (l1->val < l2->val) + { tmp->next = l1; l1 = l1->next; - } else { + } + else + { tmp->next = l2; l2 = l2->next; } @@ -44,17 +53,20 @@ struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) { /* * Recursive approach */ -struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) { - if(!l1) +struct ListNode *mergeTwoLists(struct ListNode *l1, struct ListNode *l2) +{ + if (!l1) return l2; - if(!l2) + if (!l2) return l1; - if(l1->val < l2->val) { + if (l1->val < l2->val) + { l1->next = mergeTwoLists(l1->next, l2); return l1; - } else { + } + else + { l2->next = mergeTwoLists(l1, l2->next); return l2; } } - diff --git a/leetcode/src/215.c b/leetcode/src/215.c index f883e882..7a301f5b 100644 --- a/leetcode/src/215.c +++ b/leetcode/src/215.c @@ -1,8 +1,7 @@ -int *cmpval (const void *a, const void *b) { - return *(int *)b - *(int *)a; -} +int *cmpval(const void *a, const void *b) { return *(int *)b - *(int *)a; } -int findKthLargest(int* nums, int numsSize, int k){ +int findKthLargest(int *nums, int numsSize, int k) +{ qsort(nums, numsSize, sizeof(int), cmpval); - return nums[k-1]; + return nums[k - 1]; } diff --git a/leetcode/src/217.c b/leetcode/src/217.c index 4a36a8bc..a349ef9e 100644 --- a/leetcode/src/217.c +++ b/leetcode/src/217.c @@ -1,12 +1,12 @@ -int numcmp(const void *a, const void *b) { - return *(int *)a - *(int *)b; -} +int numcmp(const void *a, const void *b) { return *(int *)a - *(int *)b; } -bool containsDuplicate(int* nums, int numsSize){ +bool containsDuplicate(int *nums, int numsSize) +{ int i; qsort(nums, numsSize, sizeof(int), numcmp); - for (i = 0; i < numsSize - 1; i++) { - if(nums[i] == nums[i+1]) + for (i = 0; i < numsSize - 1; i++) + { + if (nums[i] == nums[i + 1]) return 1; } return 0; diff --git a/leetcode/src/226.c b/leetcode/src/226.c index 63262308..ac2bf161 100644 --- a/leetcode/src/226.c +++ b/leetcode/src/226.c @@ -1,6 +1,7 @@ -struct TreeNode* invertTree(struct TreeNode* root){ +struct TreeNode *invertTree(struct TreeNode *root) +{ struct TreeNode *tmp; - if(root == NULL) + if (root == NULL) return NULL; tmp = root->left; root->left = root->right; diff --git a/leetcode/src/231.c b/leetcode/src/231.c index 9957102f..aed27b97 100644 --- a/leetcode/src/231.c +++ b/leetcode/src/231.c @@ -1,5 +1,8 @@ -bool isPowerOfTwo(int n){ - if (! n) return false; - while (n % 2 == 0) n /= 2; +bool isPowerOfTwo(int n) +{ + if (!n) + return false; + while (n % 2 == 0) + n /= 2; return n == 1; } \ No newline at end of file diff --git a/leetcode/src/234.c b/leetcode/src/234.c index 5fed1fd4..b541bf61 100644 --- a/leetcode/src/234.c +++ b/leetcode/src/234.c @@ -6,33 +6,37 @@ * }; */ -struct ListNode * reverse(struct ListNode *head) { +struct ListNode *reverse(struct ListNode *head) +{ struct ListNode *res = NULL; - while(head) { + while (head) + { struct ListNode *pre_node = head; - head = head -> next; - pre_node ->next = res; + head = head->next; + pre_node->next = res; res = pre_node; } return res; } -bool isPalindrome(struct ListNode* head){ +bool isPalindrome(struct ListNode *head) +{ struct ListNode *slow = head; struct ListNode *fast = head; struct ListNode *last; - while (fast && fast->next) { - slow = slow -> next; - fast = fast -> next -> next; + while (fast && fast->next) + { + slow = slow->next; + fast = fast->next->next; } - if(fast != NULL) - slow = slow -> next; + if (fast != NULL) + slow = slow->next; last = reverse(slow); - while(last) { + while (last) + { if (head->val != last->val) return 0; - head = head -> next; - last = last -> next; + head = head->next; + last = last->next; } return 1; } - diff --git a/leetcode/src/24.c b/leetcode/src/24.c index 9ae79813..e4ce505b 100644 --- a/leetcode/src/24.c +++ b/leetcode/src/24.c @@ -1,9 +1,9 @@ -struct ListNode* swapPairs(struct ListNode* head) { - if(!head || !head->next) +struct ListNode *swapPairs(struct ListNode *head) +{ + if (!head || !head->next) return head; struct ListNode *tmp = head->next; head->next = swapPairs(head->next->next); - tmp -> next = head; + tmp->next = head; return tmp; - } diff --git a/leetcode/src/242.c b/leetcode/src/242.c index 2fd06fb2..5d077750 100644 --- a/leetcode/src/242.c +++ b/leetcode/src/242.c @@ -1,17 +1,18 @@ -bool isAnagram(char * s, char * t){ +bool isAnagram(char *s, char *t) +{ int n = strlen(s); int m = strlen(t); - + int cnt_s[1000], cnt_t[1000]; for (int c = 97; c < 97 + 26; c++) cnt_s[c] = cnt_t[c] = 0; for (int i = 0; i < n; i++) cnt_s[s[i]]++; - + for (int i = 0; i < m; i++) cnt_t[t[i]]++; - + for (int c = 97; c < 97 + 26; c++) if (cnt_s[c] != cnt_t[c]) return false; diff --git a/leetcode/src/26.c b/leetcode/src/26.c index 3b97dc2c..c9f085f7 100644 --- a/leetcode/src/26.c +++ b/leetcode/src/26.c @@ -1,10 +1,12 @@ -int removeDuplicates(int* nums, int numsSize){ +int removeDuplicates(int *nums, int numsSize) +{ int count = 0, i; - for (i = 1; i < numsSize; i++) { - if (nums[i] == nums[i-1]) + for (i = 1; i < numsSize; i++) + { + if (nums[i] == nums[i - 1]) count++; else - nums[i-count] = nums[i]; + nums[i - count] = nums[i]; } return numsSize - count; } diff --git a/leetcode/src/268.c b/leetcode/src/268.c index 6bc72ea1..600556bd 100644 --- a/leetcode/src/268.c +++ b/leetcode/src/268.c @@ -1,6 +1,8 @@ -int missingNumber(int* nums, int numsSize){ +int missingNumber(int *nums, int numsSize) +{ int i, actual_sum = 0, sum = 0; - for(i = 0; i < numsSize; i++) { + for (i = 0; i < numsSize; i++) + { sum = sum + nums[i]; actual_sum = actual_sum + i; } diff --git a/leetcode/src/27.c b/leetcode/src/27.c index 25f32762..7ba0dee9 100644 --- a/leetcode/src/27.c +++ b/leetcode/src/27.c @@ -1,7 +1,9 @@ -int removeElement(int* nums, int numsSize, int val) { +int removeElement(int *nums, int numsSize, int val) +{ int i, start = 0; - for (i = 0; i < numsSize; i++) { - if(nums[i] != val) + for (i = 0; i < numsSize; i++) + { + if (nums[i] != val) nums[start++] = nums[i]; } return start; diff --git a/leetcode/src/278.c b/leetcode/src/278.c index b08d7694..ec292d73 100644 --- a/leetcode/src/278.c +++ b/leetcode/src/278.c @@ -1,13 +1,18 @@ // Forward declaration of isBadVersion API. bool isBadVersion(int version); -int firstBadVersion(int n) { +int firstBadVersion(int n) +{ int low = 1, high = n; - while (low <= high) { + while (low <= high) + { int mid = low + (high - low) / 2; - if(isBadVersion(mid)) { + if (isBadVersion(mid)) + { high = mid - 1; - } else { + } + else + { low = mid + 1; } } diff --git a/leetcode/src/28.c b/leetcode/src/28.c index 3704ae61..ad11969e 100644 --- a/leetcode/src/28.c +++ b/leetcode/src/28.c @@ -1,52 +1,59 @@ -/* +/* * brute force approach * time complexity: O(mn) */ -int strStr(char* haystack, char* needle) { +int strStr(char *haystack, char *needle) +{ int i = 0; int j = 0; int k = 0; int hlen = 0; int nlen = 0; - - if(needle == NULL || *needle == 0) + + if (needle == NULL || *needle == 0) return 0; - - if(haystack == NULL || *haystack == 0) + + if (haystack == NULL || *haystack == 0) return -1; - + hlen = strlen(haystack); nlen = strlen(needle); - - if(hlen < nlen) + + if (hlen < nlen) return -1; - - for(i = 0; i <= hlen - nlen; i++) { + + for (i = 0; i <= hlen - nlen; i++) + { j = 0; - if(haystack[i] != needle[j++]) + if (haystack[i] != needle[j++]) continue; - + k = i + 1; - for(; j < nlen; j++) { - if(haystack[k] != needle[j]) { + for (; j < nlen; j++) + { + if (haystack[k] != needle[j]) + { break; - } else + } + else k++; } - if(j == nlen) + if (j == nlen) return i; } return -1; } -/* ---------------------------------------------------------------------------------------- */ +/* ---------------------------------------------------------------------------------------- + */ /* * KMP algorithm * time complexity: O(m + n) */ -/* fills overlap with longest proper prefix which is also suffix for each index in needle */ +/* fills overlap with longest proper prefix which is also suffix for each index + * in needle */ void fill_overlap(char *needle, int len_needle, int *overlap) { int len = 0; @@ -54,11 +61,15 @@ void fill_overlap(char *needle, int len_needle, int *overlap) overlap[0] = 0; - for (i = 1; i < len_needle;) { - if (needle[i] == needle[len]) { + for (i = 1; i < len_needle;) + { + if (needle[i] == needle[len]) + { len++; overlap[i++] = len; - } else { + } + else + { if (len) len = overlap[len - 1]; else @@ -82,15 +93,20 @@ int strStr(char *haystack, char *needle) fill_overlap(needle, len_needle, overlap); - while (i < len_haystack) { - if (needle[j] == haystack[i]) { + while (i < len_haystack) + { + if (needle[j] == haystack[i]) + { i++; j++; } - if (j == len_needle) { + if (j == len_needle) + { return (i - j); - } else if (i < len_haystack && needle[j] != haystack[i]) { + } + else if (i < len_haystack && needle[j] != haystack[i]) + { if (j != 0) j = overlap[j - 1]; else @@ -100,5 +116,5 @@ int strStr(char *haystack, char *needle) return -1; } -/* ---------------------------------------------------------------------------------------- */ - +/* ---------------------------------------------------------------------------------------- + */ diff --git a/leetcode/src/283.c b/leetcode/src/283.c index 67cfc7d9..647bdfd6 100644 --- a/leetcode/src/283.c +++ b/leetcode/src/283.c @@ -1,12 +1,15 @@ -void moveZeroes(int* nums, int numsSize) { +void moveZeroes(int *nums, int numsSize) +{ int i = 0, start = 0; - for (i = 0; i < numsSize; i++) { + for (i = 0; i < numsSize; i++) + { if (nums[i]) nums[start++] = nums[i]; } - for (start; start < numsSize; start++) { + for (start; start < numsSize; start++) + { nums[start] = 0; } } diff --git a/leetcode/src/287.c b/leetcode/src/287.c index 71c8a1cf..1c273b9b 100644 --- a/leetcode/src/287.c +++ b/leetcode/src/287.c @@ -1,13 +1,12 @@ -int cmpval(const void *a, const void *b) { - return *(int *)a - *(int *)b; -} -int findDuplicate(int* nums, int numsSize){ +int cmpval(const void *a, const void *b) { return *(int *)a - *(int *)b; } +int findDuplicate(int *nums, int numsSize) +{ int i; qsort(nums, numsSize, sizeof(int), cmpval); - for(i = 0; i < numsSize - 1; i++) { - if(nums[i] == nums[i+1]) + for (i = 0; i < numsSize - 1; i++) + { + if (nums[i] == nums[i + 1]) return nums[i]; } return nums[i]; } - diff --git a/leetcode/src/29.c b/leetcode/src/29.c index d80bd8bb..43de4c53 100644 --- a/leetcode/src/29.c +++ b/leetcode/src/29.c @@ -1,30 +1,41 @@ -int divide(int dividend, int divisor){ +int divide(int dividend, int divisor) +{ int sign = 1; long int output = 0; - if (dividend < 0) { + if (dividend < 0) + { sign *= -1; - - } else { + } + else + { dividend *= -1; } - if (divisor < 0) { + if (divisor < 0) + { sign *= -1; - - } else { + } + else + { divisor *= -1; } - while (dividend <= divisor) { + while (dividend <= divisor) + { long int tmp = 0; long int div = divisor; - while (dividend <= div) { - tmp += (tmp+1); + while (dividend <= div) + { + tmp += (tmp + 1); dividend -= div; div += div; } - if (output >= INT_MAX) { - if (sign == -1) { + if (output >= INT_MAX) + { + if (sign == -1) + { return INT_MIN; - } else { + } + else + { return INT_MAX; } } diff --git a/leetcode/src/3.c b/leetcode/src/3.c index e64293cf..29be37ce 100644 --- a/leetcode/src/3.c +++ b/leetcode/src/3.c @@ -1,51 +1,63 @@ -int lengthOfLongestSubstring(char* str) { +int lengthOfLongestSubstring(char *str) +{ int n = strlen(str); - if(!n) return 0; + if (!n) + return 0; - int L_len = 1; // lenght of longest substring - int C_len = 1; // lenght of current substring + int L_len = 1; // lenght of longest substring + int C_len = 1; // lenght of current substring - int P_ind, i; // P_ind for previous index - int visited[256]; // visited will keep track of visiting char for the last instance. - // since there are 256 ASCII char, its size is limited to that value. + int P_ind, i; // P_ind for previous index + int visited[256]; // visited will keep track of visiting char for the last + // instance. since there are 256 ASCII char, its size is + // limited to that value. memset(visited, -1, sizeof(int) * 256); - visited[str[0]] = 0; // the index of that char will tell us that when it was visited. + visited[str[0]] = + 0; // the index of that char will tell us that when it was visited. for (i = 1; i < n; i++) { - P_ind = visited[str[i]]; + P_ind = visited[str[i]]; if (P_ind == -1 || i - C_len > P_ind) - C_len++; // if the current char was not visited earlier, or it is not the part of current substring + C_len++; // if the current char was not visited earlier, or it is + // not the part of current substring else - { // otherwise, we need to change the current/longest substring length - if (C_len > L_len) L_len = C_len; + { // otherwise, we need to change the current/longest substring length + if (C_len > L_len) + L_len = C_len; C_len = i - P_ind; } visited[str[i]] = i; } - if (C_len > L_len) L_len = C_len; + if (C_len > L_len) + L_len = C_len; return L_len; } /* Brute force */ -int lengthOfLongestSubstring(char * s){ +int lengthOfLongestSubstring(char *s) +{ int cur_max = 0, max = 0; int counter[255]; int end = 0; - memset(counter, 0, sizeof(int) *255); - while (end < strlen(s)) { - if (counter[s[end]] == 0) { + memset(counter, 0, sizeof(int) * 255); + while (end < strlen(s)) + { + if (counter[s[end]] == 0) + { counter[s[end]]++; end++; cur_max++; - } else { + } + else + { char c = s[end]; memset(counter, 0, 255 * sizeof(int)); if (cur_max >= max) max = cur_max; cur_max = 0; - while(s[end - 1] != c) + while (s[end - 1] != c) end--; } } diff --git a/leetcode/src/344.c b/leetcode/src/344.c index 82317a1d..44510f20 100644 --- a/leetcode/src/344.c +++ b/leetcode/src/344.c @@ -1,10 +1,11 @@ -void reverseString(char* s, int sSize){ +void reverseString(char *s, int sSize) +{ int last = sSize - 1, i; - for (i = 0; i < last; i++) { + for (i = 0; i < last; i++) + { char tmp = s[i]; s[i] = s[last]; s[last] = tmp; last--; } - } diff --git a/leetcode/src/35.c b/leetcode/src/35.c index 31c507c2..95ca7b23 100644 --- a/leetcode/src/35.c +++ b/leetcode/src/35.c @@ -1,6 +1,8 @@ -int searchInsert(int* nums, int numsSize, int target){ +int searchInsert(int *nums, int numsSize, int target) +{ int low = 0, high = numsSize - 1, mid; - while (low <= high) { + while (low <= high) + { mid = low + (high - low) / 2; if (target > nums[mid]) low = mid + 1; @@ -13,10 +15,13 @@ int searchInsert(int* nums, int numsSize, int target){ } /* Recursive version */ -int searchInsert(int* nums, int numsSize, int target){ +int searchInsert(int *nums, int numsSize, int target) +{ int idx = numsSize - 1; - if(numsSize>0){ - if (target > nums[idx]){ + if (numsSize > 0) + { + if (target > nums[idx]) + { return numsSize; } return searchInsert(nums, numsSize - 1, target); diff --git a/leetcode/src/367.c b/leetcode/src/367.c index 76406599..e05eb646 100644 --- a/leetcode/src/367.c +++ b/leetcode/src/367.c @@ -1,4 +1,5 @@ -bool isPerfectSquare(int num){ +bool isPerfectSquare(int num) +{ for (long i = 1; i * i <= num; i++) if (i * i == num) return true; diff --git a/leetcode/src/38.c b/leetcode/src/38.c index 872b25ca..18a7fcc6 100644 --- a/leetcode/src/38.c +++ b/leetcode/src/38.c @@ -1,29 +1,30 @@ -char * countAndSay(int n){ - - //Calculating the length of array +char *countAndSay(int n) +{ + + // Calculating the length of array double result = 1.0; - for(int i = 0; i < n - 1; i++) + for (int i = 0; i < n - 1; i++) { result *= 1.4; } - int k, j, count, convert = (int) result; - - //Creating array with the length calculated above - char * arr = malloc(convert + 4); + int k, j, count, convert = (int)result; + + // Creating array with the length calculated above + char *arr = malloc(convert + 4); arr[0] = '1'; arr[1] = '\0'; - - for(int i = 2, length; i <= n; i++) + + for (int i = 2, length; i <= n; i++) { length = strlen(arr); char newArr[length * 2]; strcpy(newArr, arr); - + k = 0; j = 0; count = 1; - + while (newArr[j] != '\0') { if (newArr[j] == newArr[j + 1]) @@ -37,12 +38,11 @@ char * countAndSay(int n){ arr[k + 1] = newArr[j]; arr[k + 2] = '\0'; j++; - k+=2; + k += 2; count = 1; } - } } - + return arr; } diff --git a/leetcode/src/387.c b/leetcode/src/387.c index 65e9d623..bb856b0f 100644 --- a/leetcode/src/387.c +++ b/leetcode/src/387.c @@ -1,10 +1,12 @@ -int firstUniqChar(char * s){ +int firstUniqChar(char *s) +{ int *arr = calloc(256, sizeof(int)); int i; - for(i = 0; i < strlen(s); i++) + for (i = 0; i < strlen(s); i++) arr[s[i]] = arr[s[i]] + 1; - for(i = 0; i < strlen(s); i++) { - if(arr[s[i]] == 1) + for (i = 0; i < strlen(s); i++) + { + if (arr[s[i]] == 1) return i; } return -1; diff --git a/leetcode/src/389.c b/leetcode/src/389.c index afcd1c52..0846934c 100644 --- a/leetcode/src/389.c +++ b/leetcode/src/389.c @@ -1,10 +1,10 @@ -char findTheDifference(char * s, char * t){ +char findTheDifference(char *s, char *t) +{ int sum1 = 0, sum2 = 0; int i; - for(i = 0; i < strlen(s); i++) - sum1+= s[i]; - for(i = 0; i < strlen(t); i++) - sum2+= t[i]; - return (char )(sum2 - sum1); - + for (i = 0; i < strlen(s); i++) + sum1 += s[i]; + for (i = 0; i < strlen(t); i++) + sum2 += t[i]; + return (char)(sum2 - sum1); } diff --git a/leetcode/src/4.c b/leetcode/src/4.c index b5a2e830..de676f44 100644 --- a/leetcode/src/4.c +++ b/leetcode/src/4.c @@ -1,40 +1,50 @@ -double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size){ - int index1=0; - int index2=0; - int v[nums1Size+nums2Size]; - int v_index=0; - - while(index1left == NULL && root->right == NULL; } -int sumOfLeftLeaves(struct TreeNode* root){ +int sumOfLeftLeaves(struct TreeNode *root) +{ if (root == NULL) return 0; - if (root->left) { - if(isleaf(root->left)) + if (root->left) + { + if (isleaf(root->left)) return root->left->val + sumOfLeftLeaves(root->right); } return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right); - } diff --git a/leetcode/src/442.c b/leetcode/src/442.c index 3e7c3094..35d558b4 100644 --- a/leetcode/src/442.c +++ b/leetcode/src/442.c @@ -1,19 +1,22 @@ -int cmpval (const void *a, const void *b) { - return *(int *)a - *(int *)b; -} +int cmpval(const void *a, const void *b) { return *(int *)a - *(int *)b; } -int* findDuplicates(int* nums, int numsSize, int* returnSize){ +int *findDuplicates(int *nums, int numsSize, int *returnSize) +{ int i; qsort(nums, numsSize, sizeof(int), cmpval); int *retArr = malloc(numsSize * sizeof(int)); *returnSize = 0; - for (i = 0; i < numsSize - 1;) { - if (nums[i] == nums[i + 1]) {\ + for (i = 0; i < numsSize - 1;) + { + if (nums[i] == nums[i + 1]) + { retArr[*returnSize] = nums[i]; *returnSize = *returnSize + 1; i = i + 2; - } else { + } + else + { i = i + 1; } } diff --git a/leetcode/src/461.c b/leetcode/src/461.c index a3ac8f99..d05b1b62 100644 --- a/leetcode/src/461.c +++ b/leetcode/src/461.c @@ -1,12 +1,20 @@ -int hammingDistance(int x, int y){ - int difference = x ^ y; //The XOR operator generates the bitwise difference in the binary representation of two numbers - //If bit in ith position of both numbers is same, bit in difference is 0, otherwise 1 - int TotalBits = sizeof(difference)*8; //total number of bits +int hammingDistance(int x, int y) +{ + int difference = + x ^ y; // The XOR operator generates the bitwise difference in the + // binary representation of two numbers If bit in ith position of + // both numbers is same, bit in difference is 0, otherwise 1 + int TotalBits = sizeof(difference) * 8; // total number of bits int i, distance = 0; - for(i = 0; i < TotalBits; i++) { - if(difference & (UINT32_C(1) << i)) //if the bit on the ith position of 32 bit input is 1, then proceed - //Further note the use of UINT32_C to convert 1 to unsigned 32 bit int, as just 1 is treated as int which cannot be shifted left more than 30 times + for (i = 0; i < TotalBits; i++) + { + if (difference & + (UINT32_C(1) + << i)) // if the bit on the ith position of 32 bit input is 1, then + // proceed Further note the use of UINT32_C to convert 1 to + // unsigned 32 bit int, as just 1 is treated as int which + // cannot be shifted left more than 30 times distance += 1; - } + } return distance; } \ No newline at end of file diff --git a/leetcode/src/476.c b/leetcode/src/476.c index f6ee952f..73a951d7 100644 --- a/leetcode/src/476.c +++ b/leetcode/src/476.c @@ -1,15 +1,24 @@ -int findComplement(int num) { +int findComplement(int num) +{ int TotalBits = 0; int temp = num; - while(temp) { //To find position of MSB in given num. Since num is represented as a standard size in memory, we cannot rely on size - //for that information. - TotalBits++; //increment TotalBits till temp becomes 0 - temp >>= 1; //shift temp right by 1 bit every iteration; temp loses 1 bit to underflow every iteration till it becomes 0 + while (temp) + { // To find position of MSB in given num. Since num is represented as a + // standard size in memory, we cannot rely on size for that information. + TotalBits++; // increment TotalBits till temp becomes 0 + temp >>= 1; // shift temp right by 1 bit every iteration; temp loses 1 + // bit to underflow every iteration till it becomes 0 } - int i, flipNumber = 1; //Eg: 1's complement of 101(binary) can be found as 101^111 (XOR with 111 flips all bits that are 1 to 0 and flips 0 to 1) - for(i = 1; i < TotalBits; i++) { - flipNumber += UINT32_C(1) << i; //Note the use of unsigned int to facilitate left shift more than 31 times, if needed + int i, + flipNumber = + 1; // Eg: 1's complement of 101(binary) can be found as 101^111 (XOR + // with 111 flips all bits that are 1 to 0 and flips 0 to 1) + for (i = 1; i < TotalBits; i++) + { + flipNumber += UINT32_C(1) + << i; // Note the use of unsigned int to facilitate left + // shift more than 31 times, if needed } - num = num^flipNumber; + num = num ^ flipNumber; return num; } \ No newline at end of file diff --git a/leetcode/src/509.c b/leetcode/src/509.c index 5afd1d1c..8129354b 100644 --- a/leetcode/src/509.c +++ b/leetcode/src/509.c @@ -1,7 +1,8 @@ -int fib(int N){ - if(N == 0) +int fib(int N) +{ + if (N == 0) return 0; - if(N == 1) + if (N == 1) return 1; return fib(N - 1) + fib(N - 2); } diff --git a/leetcode/src/520.c b/leetcode/src/520.c index 86a2c123..399c1c89 100644 --- a/leetcode/src/520.c +++ b/leetcode/src/520.c @@ -1,10 +1,12 @@ -bool detectCapitalUse(char * word){ +bool detectCapitalUse(char *word) +{ int len = strlen(word); - if(len == 1) + if (len == 1) return 1; int countUpper = 0, i; - for(i = 0; i < len; i++) { - if(isupper(word[i])) + for (i = 0; i < len; i++) + { + if (isupper(word[i])) countUpper++; } /* All lower case */ @@ -19,21 +21,23 @@ bool detectCapitalUse(char * word){ } /* Another way */ -bool isAllUpper(char *word) { +bool isAllUpper(char *word) +{ int len = strlen(word); - for(int i = 0; i < len; i++) { - if(islower(word[i])) + for (int i = 0; i < len; i++) + { + if (islower(word[i])) return 0; } return 1; } -bool detectCapitalUse(char * word){ +bool detectCapitalUse(char *word) +{ int len = strlen(word); - for(int i = 1; i < len; i++) { - if(isupper(word[i]) && !isAllUpper(word)) + for (int i = 1; i < len; i++) + { + if (isupper(word[i]) && !isAllUpper(word)) return 0; } return 1; } - - diff --git a/leetcode/src/53.c b/leetcode/src/53.c index 92547169..78351c25 100644 --- a/leetcode/src/53.c +++ b/leetcode/src/53.c @@ -1,11 +1,11 @@ -int maxcmp(int a, int b) { - return a >= b ? a : b; -} +int maxcmp(int a, int b) { return a >= b ? a : b; } -int maxSubArray(int* nums, int numsSize){ +int maxSubArray(int *nums, int numsSize) +{ int maxSoFar = nums[0], maxEndingHere = nums[0]; - for(int i = 1; i < numsSize; i++) { + for (int i = 1; i < numsSize; i++) + { maxEndingHere = maxcmp(maxEndingHere + nums[i], nums[i]); maxSoFar = maxcmp(maxSoFar, maxEndingHere); } diff --git a/leetcode/src/561.c b/leetcode/src/561.c index 85129793..b090fccc 100644 --- a/leetcode/src/561.c +++ b/leetcode/src/561.c @@ -1,10 +1,9 @@ -int cmpval (const void *a, const void *b) { - return *(int *)a - *(int *)b; -} -int arrayPairSum(int* nums, int numsSize){ +int cmpval(const void *a, const void *b) { return *(int *)a - *(int *)b; } +int arrayPairSum(int *nums, int numsSize) +{ int sum = 0, i; qsort(nums, numsSize, sizeof(int), cmpval); - for(i = 0; i < numsSize; i = i + 2) + for (i = 0; i < numsSize; i = i + 2) sum = sum + nums[i]; return sum; } diff --git a/leetcode/src/617.c b/leetcode/src/617.c index 1a6da56d..95fca003 100644 --- a/leetcode/src/617.c +++ b/leetcode/src/617.c @@ -1,16 +1,20 @@ -struct TreeNode * newNode (int item) { - struct TreeNode *node = (struct TreeNode *)malloc(sizeof(struct TreeNode)); +struct TreeNode *newNode(int item) +{ + struct TreeNode *node = (struct TreeNode *)malloc(sizeof(struct TreeNode)); node->val = item; node->left = node->right = NULL; return node; } -struct TreeNode* mergeTrees(struct TreeNode* t1, struct TreeNode* t2){ +struct TreeNode *mergeTrees(struct TreeNode *t1, struct TreeNode *t2) +{ if (t1 == NULL && t2 == NULL) return NULL; int item = (t1 == NULL ? 0 : t1->val) + (t2 == NULL ? 0 : t2->val); struct TreeNode *node = newNode(item); - node->left = mergeTrees(t1 == NULL ? NULL : t1->left, t2 == NULL ? NULL : t2->left); - node->right = mergeTrees(t1 == NULL ? NULL : t1->right, t2 == NULL ? NULL : t2->right); + node->left = + mergeTrees(t1 == NULL ? NULL : t1->left, t2 == NULL ? NULL : t2->left); + node->right = mergeTrees(t1 == NULL ? NULL : t1->right, + t2 == NULL ? NULL : t2->right); return node; } diff --git a/leetcode/src/647.c b/leetcode/src/647.c index d78d2439..fa3a0bdc 100644 --- a/leetcode/src/647.c +++ b/leetcode/src/647.c @@ -1,23 +1,25 @@ /* Author : Saurav Dubey */ - -int countSubstrings(char* s) { +int countSubstrings(char *s) +{ int len = strlen(s); int i; int count = 0; - for( i=0; i=0 && tail+1= 0 && tail + 1 < len) + ret += countPalin(s, head - 1, tail + 1, len); return ret; } diff --git a/leetcode/src/66.c b/leetcode/src/66.c index bfeec04e..e312940a 100644 --- a/leetcode/src/66.c +++ b/leetcode/src/66.c @@ -1,22 +1,28 @@ /** * Note: The returned array must be malloced, assume caller calls free(). */ -int* plusOne(int* digits, int digitsSize, int* returnSize){ - for (int i = digitsSize-1; i >= 0; i--) { - if (digits[i] < 9) { +int *plusOne(int *digits, int digitsSize, int *returnSize) +{ + for (int i = digitsSize - 1; i >= 0; i--) + { + if (digits[i] < 9) + { digits[i]++; *returnSize = digitsSize; return digits; - } else { + } + else + { digits[i] = 0; } } - int* newdigit = (int*)malloc((digitsSize+1) * sizeof(int)); + int *newdigit = (int *)malloc((digitsSize + 1) * sizeof(int)); newdigit[0] = 1; - for (int i = 1; i < (digitsSize+1); i++) { - newdigit[i] = digits[i-1]; + for (int i = 1; i < (digitsSize + 1); i++) + { + newdigit[i] = digits[i - 1]; } - *returnSize = digitsSize+1; + *returnSize = digitsSize + 1; return newdigit; } \ No newline at end of file diff --git a/leetcode/src/674.c b/leetcode/src/674.c index 9f486d03..1bf68980 100644 --- a/leetcode/src/674.c +++ b/leetcode/src/674.c @@ -1,16 +1,20 @@ -int findLengthOfLCIS(int* nums, int numsSize){ +int findLengthOfLCIS(int *nums, int numsSize) +{ int maxval = 1, i, count = 1; if (numsSize == 0) return 0; - for (i = 1; i < numsSize; i++) { - if(nums[i] > nums[i -1]) { + for (i = 1; i < numsSize; i++) + { + if (nums[i] > nums[i - 1]) + { count++; if (count >= maxval) maxval = count; - } else { + } + else + { count = 1; } } return maxval; } - diff --git a/leetcode/src/7.c b/leetcode/src/7.c index 1bc03434..5b4f7677 100644 --- a/leetcode/src/7.c +++ b/leetcode/src/7.c @@ -1,13 +1,17 @@ #include -int reverse(int x){ +int reverse(int x) +{ int rev = 0; - while (x != 0) { - int pop = x % 10; - x /= 10; - if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0; - if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0; - rev = rev * 10 + pop; - } - return rev; + while (x != 0) + { + int pop = x % 10; + x /= 10; + if (rev > INT_MAX / 10 || (rev == INT_MAX / 10 && pop > 7)) + return 0; + if (rev < INT_MIN / 10 || (rev == INT_MIN / 10 && pop < -8)) + return 0; + rev = rev * 10 + pop; + } + return rev; } diff --git a/leetcode/src/700.c b/leetcode/src/700.c index c8ce6335..73cc1a5a 100644 --- a/leetcode/src/700.c +++ b/leetcode/src/700.c @@ -7,16 +7,21 @@ * }; */ - -struct TreeNode* searchBST(struct TreeNode* root, int val){ - if(!root) +struct TreeNode *searchBST(struct TreeNode *root, int val) +{ + if (!root) return NULL; - if (root->val == val) { + if (root->val == val) + { return root; - } else if (root->val > val) { + } + else if (root->val > val) + { return searchBST(root->left, val); - } else { + } + else + { return searchBST(root->right, val); } } diff --git a/leetcode/src/701.c b/leetcode/src/701.c index 422f884f..3f7b7c97 100644 --- a/leetcode/src/701.c +++ b/leetcode/src/701.c @@ -1,10 +1,14 @@ -struct TreeNode* insertIntoBST(struct TreeNode* root, int val){ - if(root == NULL) { +struct TreeNode *insertIntoBST(struct TreeNode *root, int val) +{ + if (root == NULL) + { struct TreeNode *new_val = malloc(sizeof(struct TreeNode)); new_val->val = val; new_val->left = new_val->right = NULL; return new_val; - } else { + } + else + { if (root->val >= val) root->left = insertIntoBST(root->left, val); else diff --git a/leetcode/src/704.c b/leetcode/src/704.c index 28921745..8dd2891c 100644 --- a/leetcode/src/704.c +++ b/leetcode/src/704.c @@ -1,12 +1,19 @@ -int search(int* nums, int numsSize, int target){ +int search(int *nums, int numsSize, int target) +{ int low = 0, high = numsSize - 1; - while (low <= high) { + while (low <= high) + { int mid = low + (high - low) / 2; - if (target > nums[mid]) { + if (target > nums[mid]) + { low = mid + 1; - } else if (target < nums[mid]) { + } + else if (target < nums[mid]) + { high = mid - 1; - } else { + } + else + { return mid; } } @@ -14,15 +21,13 @@ int search(int* nums, int numsSize, int target){ } /* Another solution: Using bsearch() */ -int cmpint (const void *a, const void *b) { - return *(int *) a - *(int *)b; -} +int cmpint(const void *a, const void *b) { return *(int *)a - *(int *)b; } -int search(int* nums, int numsSize, int target){ +int search(int *nums, int numsSize, int target) +{ int *ret = bsearch(&target, nums, numsSize, sizeof(int), cmpint); if (ret) return (ret - nums); else return -1; } - diff --git a/leetcode/src/709.c b/leetcode/src/709.c index c231f0f8..032c1ecd 100644 --- a/leetcode/src/709.c +++ b/leetcode/src/709.c @@ -1,5 +1,6 @@ -char * toLowerCase(char * str){ - for (int i = 0; i< strlen(str); i++) +char *toLowerCase(char *str) +{ + for (int i = 0; i < strlen(str); i++) str[i] = tolower(str[i]); return str; } diff --git a/leetcode/src/771.c b/leetcode/src/771.c index 6fca4d27..eabc9d4f 100644 --- a/leetcode/src/771.c +++ b/leetcode/src/771.c @@ -1,7 +1,8 @@ // for strlen() #include -int numJewelsInStones(char * j, char * s) { +int numJewelsInStones(char *j, char *s) +{ // as strlen is O(n), store it once rather than using it in for loop int cnt[500], lens = strlen(s), lenj = strlen(j), sol = 0; memset(cnt, 0, sizeof(cnt)); @@ -16,4 +17,3 @@ int numJewelsInStones(char * j, char * s) { return sol; } - diff --git a/leetcode/src/8.c b/leetcode/src/8.c index 91c4d736..bf3f905d 100644 --- a/leetcode/src/8.c +++ b/leetcode/src/8.c @@ -1,60 +1,78 @@ -int myAtoi(char * str){ +int myAtoi(char *str) +{ int minusFlag = 0; int length = strlen(str); long int result = 0; char numberBuffer[11]; int counter = 0; - while(str[counter] == ' '){ + while (str[counter] == ' ') + { counter++; } str = &str[counter]; counter = 0; - - for(int i=0; i10){ - if(minusFlag){ - return __INT_MAX__*-1-1; - } else { + if (counter > 10) + { + if (minusFlag) + { + return __INT_MAX__ * -1 - 1; + } + else + { return __INT_MAX__; } } - if(str[i] < '0' || str[i] > '9'){ + if (str[i] < '0' || str[i] > '9') + { break; } - if(counter == 0 && str[i] == '0'){ + if (counter == 0 && str[i] == '0') + { continue; } - - numberBuffer[counter]= str[i]; + + numberBuffer[counter] = str[i]; counter++; } int i = 0; - while(counter > 0) { - if(minusFlag){ - result -= (numberBuffer[i] - '0')*pow(10.0, counter-1); - }else{ - result += (numberBuffer[i] - '0')*pow(10.0, counter-1); + while (counter > 0) + { + if (minusFlag) + { + result -= (numberBuffer[i] - '0') * pow(10.0, counter - 1); + } + else + { + result += (numberBuffer[i] - '0') * pow(10.0, counter - 1); } i++; counter--; } - - if(result > __INT_MAX__){ + + if (result > __INT_MAX__) + { return __INT_MAX__; - } else if(result < __INT_MAX__*-1-1){ - return __INT_MAX__*-1-1; + } + else if (result < __INT_MAX__ * -1 - 1) + { + return __INT_MAX__ * -1 - 1; } return result; } - diff --git a/leetcode/src/82.c b/leetcode/src/82.c index 064a176b..6f784c59 100644 --- a/leetcode/src/82.c +++ b/leetcode/src/82.c @@ -1,14 +1,19 @@ -struct ListNode* deleteDuplicates(struct ListNode* head) { +struct ListNode *deleteDuplicates(struct ListNode *head) +{ if (head == NULL) return NULL; - if (head->next && head->val == head->next->val) { + if (head->next && head->val == head->next->val) + { /* Remove all duplicate numbers */ - while (head->next && head->val == head->next->val) { - head = head -> next; + while (head->next && head->val == head->next->val) + { + head = head->next; } return deleteDuplicates(head->next); - } else { + } + else + { head->next = deleteDuplicates(head->next); } return head; diff --git a/leetcode/src/83.c b/leetcode/src/83.c index 3411c296..c1848a08 100644 --- a/leetcode/src/83.c +++ b/leetcode/src/83.c @@ -1,8 +1,10 @@ -struct ListNode* deleteDuplicates(struct ListNode* head) { - struct ListNode* cur = head; - while (cur && cur->next) { - if(cur->val == cur->next->val) +struct ListNode *deleteDuplicates(struct ListNode *head) +{ + struct ListNode *cur = head; + while (cur && cur->next) + { + if (cur->val == cur->next->val) cur->next = cur->next->next; else cur = cur->next; diff --git a/leetcode/src/852.c b/leetcode/src/852.c index d658c9d2..2b485d55 100644 --- a/leetcode/src/852.c +++ b/leetcode/src/852.c @@ -1,10 +1,12 @@ -int peakIndexInMountainArray(int* A, int ASize) { +int peakIndexInMountainArray(int *A, int ASize) +{ int low = 1, high = ASize; - while (low <= high) { + while (low <= high) + { int mid = low + (high - low) / 2; if (A[mid - 1] < A[mid] && A[mid] > A[mid + 1]) return mid; - else if(A[mid - 1] < A[mid] && A[mid] < A[mid + 1]) + else if (A[mid - 1] < A[mid] && A[mid] < A[mid + 1]) low = mid + 1; else high = mid - 1; diff --git a/leetcode/src/876.c b/leetcode/src/876.c index 7124178f..b3b3a0a2 100644 --- a/leetcode/src/876.c +++ b/leetcode/src/876.c @@ -6,14 +6,14 @@ * }; */ - -struct ListNode* middleNode(struct ListNode* head){ +struct ListNode *middleNode(struct ListNode *head) +{ struct ListNode *fast, *slow; fast = slow = head; - while(fast && fast->next) { - slow = slow -> next; - fast = fast -> next -> next; + while (fast && fast->next) + { + slow = slow->next; + fast = fast->next->next; } return slow; } - diff --git a/leetcode/src/9.c b/leetcode/src/9.c index 28d05a0c..29c99c16 100644 --- a/leetcode/src/9.c +++ b/leetcode/src/9.c @@ -1,13 +1,16 @@ -bool isPalindrome(int x){ - if(x < 0 || (x % 10 == 0 && x != 0)) { +bool isPalindrome(int x) +{ + if (x < 0 || (x % 10 == 0 && x != 0)) + { return false; } int revertedNumber = 0; - while(x > revertedNumber) { + while (x > revertedNumber) + { revertedNumber = revertedNumber * 10 + x % 10; x /= 10; } - return x == revertedNumber || x == revertedNumber/10; + return x == revertedNumber || x == revertedNumber / 10; } diff --git a/leetcode/src/905.c b/leetcode/src/905.c index f6cb7015..802b97f0 100644 --- a/leetcode/src/905.c +++ b/leetcode/src/905.c @@ -10,16 +10,21 @@ * * Note: The returned array must be malloced, assume caller calls free(). */ -int* sortArrayByParity(int* A, int ASize, int* returnSize) { +int *sortArrayByParity(int *A, int ASize, int *returnSize) +{ int *retArr = malloc(ASize * sizeof(int)); int oddIndex = ASize - 1; int evenIndex = 0; *returnSize = ASize; - for (int i = 0; i < ASize; i++) { - if (A[i] % 2 == 0) { + for (int i = 0; i < ASize; i++) + { + if (A[i] % 2 == 0) + { retArr[evenIndex] = A[i]; evenIndex++; - } else { + } + else + { retArr[oddIndex] = A[i]; oddIndex--; } diff --git a/leetcode/src/917.c b/leetcode/src/917.c index f1cc6185..fae38a90 100644 --- a/leetcode/src/917.c +++ b/leetcode/src/917.c @@ -1,11 +1,15 @@ -char * reverseOnlyLetters(char * S){ +char *reverseOnlyLetters(char *S) +{ int last = strlen(S) - 1, i; - for(i = 0; i < last;) { - if(!isalpha(S[i])) { + for (i = 0; i < last;) + { + if (!isalpha(S[i])) + { i++; continue; } - if(!isalpha(S[last])) { + if (!isalpha(S[last])) + { last--; continue; } @@ -17,4 +21,3 @@ char * reverseOnlyLetters(char * S){ } return S; } - diff --git a/leetcode/src/938.c b/leetcode/src/938.c index e1f84763..7c6636a8 100644 --- a/leetcode/src/938.c +++ b/leetcode/src/938.c @@ -1,9 +1,16 @@ -int rangeSumBST(struct TreeNode* root, int L, int R){ - if (root == NULL) { +int rangeSumBST(struct TreeNode *root, int L, int R) +{ + if (root == NULL) + { return 0; - } else if (root->val >= L && root->val <= R) { - return root->val + rangeSumBST(root->left, L, R) + rangeSumBST(root->right, L, R); - } else { + } + else if (root->val >= L && root->val <= R) + { + return root->val + rangeSumBST(root->left, L, R) + + rangeSumBST(root->right, L, R); + } + else + { return rangeSumBST(root->left, L, R) + rangeSumBST(root->right, L, R); } } diff --git a/leetcode/src/94.c b/leetcode/src/94.c index 4a44a676..d9abcc45 100644 --- a/leetcode/src/94.c +++ b/leetcode/src/94.c @@ -1,5 +1,6 @@ -void processTraversal(struct TreeNode *root, int *res, int *size) { - if(!root) +void processTraversal(struct TreeNode *root, int *res, int *size) +{ + if (!root) return; processTraversal(root->left, res, size); res[*size] = root->val; @@ -7,8 +8,9 @@ void processTraversal(struct TreeNode *root, int *res, int *size) { processTraversal(root->right, res, size); } -int* inorderTraversal(struct TreeNode* root, int* returnSize){ - int *res = malloc(256*sizeof(int)); +int *inorderTraversal(struct TreeNode *root, int *returnSize) +{ + int *res = malloc(256 * sizeof(int)); *returnSize = 0; processTraversal(root, res, returnSize); return res; diff --git a/leetcode/src/965.c b/leetcode/src/965.c index 162cae78..0892be6c 100644 --- a/leetcode/src/965.c +++ b/leetcode/src/965.c @@ -1,12 +1,15 @@ -bool isUnivalTree(struct TreeNode* root){ +bool isUnivalTree(struct TreeNode *root) +{ if (root == NULL) return 1; - if (root->left) { - if(root->left->val != root->val) + if (root->left) + { + if (root->left->val != root->val) return 0; } - if (root->right) { - if(root->right->val != root->val) + if (root->right) + { + if (root->right->val != root->val) return 0; } return isUnivalTree(root->left) && isUnivalTree(root->right); diff --git a/leetcode/src/977.c b/leetcode/src/977.c index 93fb8100..960bd8f6 100644 --- a/leetcode/src/977.c +++ b/leetcode/src/977.c @@ -1,13 +1,18 @@ /* 1st way: Using 2 pointers */ -int* sortedSquares(int* A, int ASize, int* returnSize){ +int *sortedSquares(int *A, int ASize, int *returnSize) +{ int i, start = 0, end = ASize - 1; int *res = malloc(ASize * sizeof(int)); *returnSize = ASize; - for (i = ASize - 1; i >= 0; i--) { - if (abs(A[start]) > A[end]) { + for (i = ASize - 1; i >= 0; i--) + { + if (abs(A[start]) > A[end]) + { res[i] = A[start] * A[start]; start++; - } else { + } + else + { res[i] = A[end] * A[end]; end--; } @@ -16,11 +21,10 @@ int* sortedSquares(int* A, int ASize, int* returnSize){ } /* 2nd way: Using qsort */ -int cmpval(const void *a, const void *b) { - return *(int *)a - *(int *)b; -} +int cmpval(const void *a, const void *b) { return *(int *)a - *(int *)b; } -int* sortedSquares(int* A, int ASize, int* returnSize) { +int *sortedSquares(int *A, int ASize, int *returnSize) +{ int *res = malloc(ASize * sizeof(int)); for (int i = 0; i < ASize; i++) res[i] = A[i] * A[i]; diff --git a/misc/Collatz.c b/misc/Collatz.c index 770e1004..a99140ea 100644 --- a/misc/Collatz.c +++ b/misc/Collatz.c @@ -1,6 +1,7 @@ /* -collatz conjecture: a series for a number n in which if n even then the next number is n/2 ,but if n is odd then the next number is 3n+1. -this series continues till it reaches 1*/ +collatz conjecture: a series for a number n in which if n even then the next +number is n/2 ,but if n is odd then the next number is 3n+1. this series +continues till it reaches 1*/ #include #include @@ -13,18 +14,18 @@ int main(int argc, char *argv[]) else { printf("Enter starting number: "); - scanf("%lu", &n); //input number + scanf("%lu", &n); // input number } - curr_no = n; //curr_no stores input number n - while (curr_no != 1) //loop till series reaches 1 + curr_no = n; // curr_no stores input number n + while (curr_no != 1) // loop till series reaches 1 { num_steps++; printf("%llu->", curr_no); - if (curr_no % 2 == 0) //condition for even number + if (curr_no % 2 == 0) // condition for even number curr_no = curr_no / 2; else - curr_no = (curr_no * 3) + 1; //condition for odd number + curr_no = (curr_no * 3) + 1; // condition for odd number } printf("1\nNumber of steps: %llu\n", num_steps); return 0; diff --git a/misc/Factorial.c b/misc/Factorial.c index f85077e8..1c5ae566 100644 --- a/misc/Factorial.c +++ b/misc/Factorial.c @@ -1,32 +1,32 @@ -#include +#include int main() { - int a[200],n,counter,temp,i; - a[0]=1; - counter=0; + int a[200], n, counter, temp, i; + a[0] = 1; + counter = 0; printf("Enter a whole number to Find its Factorial: "); - scanf("%d",&n); - if(n<0) - printf("Cannot Calculate factorials for negative numbers."); - else{ - for(; n>=2; n--) + scanf("%d", &n); + if (n < 0) + printf("Cannot Calculate factorials for negative numbers."); + else { - temp=0; - for(i=0; i<=counter; i++) + for (; n >= 2; n--) { - temp=(a[i]*n)+temp; - a[i]=temp%10; - temp=temp/10; - } - while(temp>0) - { - a[++counter]=temp%10; - temp=temp/10; + temp = 0; + for (i = 0; i <= counter; i++) + { + temp = (a[i] * n) + temp; + a[i] = temp % 10; + temp = temp / 10; + } + while (temp > 0) + { + a[++counter] = temp % 10; + temp = temp / 10; + } } + for (i = counter; i >= 0; i--) + printf("%d", a[i]); } - for(i=counter; i>=0; i--) - printf("%d",a[i]); - } return 0; - } diff --git a/misc/Fibonacci.c b/misc/Fibonacci.c index bc2a6000..3af48962 100644 --- a/misc/Fibonacci.c +++ b/misc/Fibonacci.c @@ -1,19 +1,23 @@ #include -//Fibonnacci function -int fib(int number){ - if(number==1||number==2) return 1; - else return fib(number-1)+fib(number-2); +// Fibonnacci function +int fib(int number) +{ + if (number == 1 || number == 2) + return 1; + else + return fib(number - 1) + fib(number - 2); } -int main(){ - int number; +int main() +{ + int number; - //Asks for the number that is in n position in Fibonnacci sequence - printf("Number: "); - scanf("%d", &number); - - printf("%d \n", fib(number)); - - return 0; + // Asks for the number that is in n position in Fibonnacci sequence + printf("Number: "); + scanf("%d", &number); + + printf("%d \n", fib(number)); + + return 0; } \ No newline at end of file diff --git a/misc/Fibonacci_DP.c b/misc/Fibonacci_DP.c index c3c55782..7bc6af55 100644 --- a/misc/Fibonacci_DP.c +++ b/misc/Fibonacci_DP.c @@ -1,4 +1,4 @@ -//Fibonacci Series using Dynamic Programming +// Fibonacci Series using Dynamic Programming /* Author: Moinak Banerjee(moinak878) Date : 1 October ,2019 @@ -9,14 +9,15 @@ int fib(int n) { - //Out of Range checking + // Out of Range checking if (n < 0) { printf("\nNo Such term !\n"); exit(0); } - //declaring array to store fibonacci numbers -- memoization - int *f = (int *)malloc((n + 2) * sizeof(int)); // one extra to handle edge case, n = 0 + // declaring array to store fibonacci numbers -- memoization + int *f = (int *)malloc( + (n + 2) * sizeof(int)); // one extra to handle edge case, n = 0 int i; /* let 0th and 1st number of the series be 0 and 1*/ @@ -38,7 +39,7 @@ int main(int argc, char *argv[]) { int number; - //Asks for the number/position of term in Fibonnacci sequence + // Asks for the number/position of term in Fibonnacci sequence if (argc == 2) number = atoi(argv[1]); else diff --git a/misc/Fibonacci_fast.c b/misc/Fibonacci_fast.c index 4db1b4b8..653ecfd4 100644 --- a/misc/Fibonacci_fast.c +++ b/misc/Fibonacci_fast.c @@ -9,9 +9,9 @@ \f} */ +#include #include #include -#include /** Returns the \f$n^{th}\f$ and \f$n+1^{th}\f$ Fibonacci number. @@ -19,7 +19,7 @@ */ void fib(unsigned long n, unsigned long *C, unsigned long *D) { - //Out of Range checking + // Out of Range checking if (n < 0) { printf("\nNo Such term !\n"); @@ -64,7 +64,7 @@ int main(int argc, char *argv[]) setlocale(LC_NUMERIC, ""); // format the printf output - //Asks for the number/position of term in Fibonnacci sequence + // Asks for the number/position of term in Fibonnacci sequence if (argc == 2) number = atoi(argv[1]); else diff --git a/misc/GCD.c b/misc/GCD.c index 771d25cf..5b25b500 100644 --- a/misc/GCD.c +++ b/misc/GCD.c @@ -1,13 +1,15 @@ #include // Euclid's algorithm -int GCD(int x, int y) { +int GCD(int x, int y) +{ if (y == 0) return x; - return GCD(y, x%y); + return GCD(y, x % y); } -int main() { +int main() +{ int a, b; printf("Input two numbers:\n"); scanf("%d %d", &a, &b); diff --git a/misc/LCM.c b/misc/LCM.c index 6f62bad2..c1f7487f 100644 --- a/misc/LCM.c +++ b/misc/LCM.c @@ -1,35 +1,32 @@ -// C program to find LCM of two numbers +// C program to find LCM of two numbers /* - suppose we have two numbers a and b. - Property: Since product of LCM and GCD of two numbers are equal to product of that number itself. - i.e, LCM(a,b)*GCD(a,b)=a*b. - So,here we first find the GCD of two numbers and using above property we find LCM of that two numbers. + suppose we have two numbers a and b. + Property: Since product of LCM and GCD of two numbers are equal to product + of that number itself. i.e, LCM(a,b)*GCD(a,b)=a*b. So,here we first find the + GCD of two numbers and using above property we find LCM of that two numbers. */ -#include - -// Recursive function to return gcd of a and b -int gcd(int a, int b) -{ - if (a == 0) - return b; - return gcd(b % a, a); -} - -// Function to return LCM of two numbers -int lcm(int a, int b) -{ - return (a*b)/gcd(a, b); -} - -// Driver program -int main() -{ - int a,b; +#include + +// Recursive function to return gcd of a and b +int gcd(int a, int b) +{ + if (a == 0) + return b; + return gcd(b % a, a); +} + +// Function to return LCM of two numbers +int lcm(int a, int b) { return (a * b) / gcd(a, b); } + +// Driver program +int main() +{ + int a, b; printf("Enter two numbers to find their LCM \n"); - scanf("%d%d",&a,&b); - printf("LCM of %d and %d is %d ", a, b, lcm(a, b)); - return 0; -} + scanf("%d%d", &a, &b); + printf("LCM of %d and %d is %d ", a, b, lcm(a, b)); + return 0; +} /* Test Case1: a=15,b=20 diff --git a/misc/Large_Factorials.c b/misc/Large_Factorials.c index 64f6eb25..b0477dd6 100644 --- a/misc/Large_Factorials.c +++ b/misc/Large_Factorials.c @@ -1,44 +1,51 @@ #include -int main(){ +int main() +{ - int a[16500], T; - long long int i, j; + int a[16500], T; + long long int i, j; - printf("Enter number of test cases : "); - scanf("%d", &T); + printf("Enter number of test cases : "); + scanf("%d", &T); - while(T--){ - for(i=0; i<16500; i++){ - a[i]=0; - } + while (T--) + { + for (i = 0; i < 16500; i++) + { + a[i] = 0; + } - a[1]=1; - int N, carry=0, count=0; - printf("Enter a number : "); - scanf("%d", &N); + a[1] = 1; + int N, carry = 0, count = 0; + printf("Enter a number : "); + scanf("%d", &N); - for(i=1; i<=N; i++){ - carry=0; - for(j=0; j<16500; j++){ - a[j]=a[j]*i+carry; - carry=a[j]/10; - a[j]=a[j]%10; - } - } + for (i = 1; i <= N; i++) + { + carry = 0; + for (j = 0; j < 16500; j++) + { + a[j] = a[j] * i + carry; + carry = a[j] / 10; + a[j] = a[j] % 10; + } + } - for(i=0; i<16500; i++){ - if(a[i]!=0){ - count=i; - } - } + for (i = 0; i < 16500; i++) + { + if (a[i] != 0) + { + count = i; + } + } - for(i=count; i>0; i--){ - printf("%d", a[i]); - } - printf("\n"); + for (i = count; i > 0; i--) + { + printf("%d", a[i]); + } + printf("\n"); + } - } - - return 0; + return 0; } diff --git a/misc/Longest_SubSequence.c b/misc/Longest_SubSequence.c index b1d74a41..23d506f8 100644 --- a/misc/Longest_SubSequence.c +++ b/misc/Longest_SubSequence.c @@ -1,88 +1,104 @@ #include #include +void longestSub(int *ARRAY, int ARRAY_LENGTH, int **RESULT, int *RESULT_LENGTH) +{ // RESULT and RESULT_LENGTH will be modified by their pointers -void longestSub(int* ARRAY,int ARRAY_LENGTH, int** RESULT,int* RESULT_LENGTH){ //RESULT and RESULT_LENGTH will be modified by their pointers - - if(ARRAY_LENGTH <= 1){ - *RESULT=ARRAY; - *RESULT_LENGTH = ARRAY_LENGTH; - } - else{ - int PIVOT = ARRAY[0]; - int *LONGEST_SUB = NULL; - int i, j, LONGEST_SUB_LENGTH = 0; - int TEMPORARY_ARRAY_LENGTH = 0, *TEMPORARY_ARRAY = NULL; + if (ARRAY_LENGTH <= 1) + { + *RESULT = ARRAY; + *RESULT_LENGTH = ARRAY_LENGTH; + } + else + { + int PIVOT = ARRAY[0]; + int *LONGEST_SUB = NULL; + int i, j, LONGEST_SUB_LENGTH = 0; + int TEMPORARY_ARRAY_LENGTH = 0, *TEMPORARY_ARRAY = NULL; - for(i = 1; i < ARRAY_LENGTH; i++){ - if (ARRAY[i] < PIVOT){ - - TEMPORARY_ARRAY_LENGTH = 0; - TEMPORARY_ARRAY = NULL; + for (i = 1; i < ARRAY_LENGTH; i++) + { + if (ARRAY[i] < PIVOT) + { - for(j = i+1;j < ARRAY_LENGTH; j++){ - if(ARRAY[j] >= ARRAY[i]){ + TEMPORARY_ARRAY_LENGTH = 0; + TEMPORARY_ARRAY = NULL; - TEMPORARY_ARRAY_LENGTH++; - TEMPORARY_ARRAY = (int *)realloc(TEMPORARY_ARRAY, TEMPORARY_ARRAY_LENGTH*sizeof(int)); - TEMPORARY_ARRAY[TEMPORARY_ARRAY_LENGTH-1] = ARRAY[j]; - } - } + for (j = i + 1; j < ARRAY_LENGTH; j++) + { + if (ARRAY[j] >= ARRAY[i]) + { - longestSub(TEMPORARY_ARRAY, TEMPORARY_ARRAY_LENGTH, &TEMPORARY_ARRAY, &TEMPORARY_ARRAY_LENGTH); - if(LONGEST_SUB_LENGTH < TEMPORARY_ARRAY_LENGTH + 1){ + TEMPORARY_ARRAY_LENGTH++; + TEMPORARY_ARRAY = (int *)realloc( + TEMPORARY_ARRAY, + TEMPORARY_ARRAY_LENGTH * sizeof(int)); + TEMPORARY_ARRAY[TEMPORARY_ARRAY_LENGTH - 1] = ARRAY[j]; + } + } - LONGEST_SUB_LENGTH = TEMPORARY_ARRAY_LENGTH + 1; - LONGEST_SUB = (int *)realloc(LONGEST_SUB, LONGEST_SUB_LENGTH*sizeof(int)); - LONGEST_SUB[0] = ARRAY[i]; + longestSub(TEMPORARY_ARRAY, TEMPORARY_ARRAY_LENGTH, + &TEMPORARY_ARRAY, &TEMPORARY_ARRAY_LENGTH); + if (LONGEST_SUB_LENGTH < TEMPORARY_ARRAY_LENGTH + 1) + { - for(i = 1;i < LONGEST_SUB_LENGTH; i++) - LONGEST_SUB[i] = TEMPORARY_ARRAY[i-1]; - } - } - } + LONGEST_SUB_LENGTH = TEMPORARY_ARRAY_LENGTH + 1; + LONGEST_SUB = (int *)realloc( + LONGEST_SUB, LONGEST_SUB_LENGTH * sizeof(int)); + LONGEST_SUB[0] = ARRAY[i]; - TEMPORARY_ARRAY = NULL; - TEMPORARY_ARRAY_LENGTH = 0; - for(i = 1;i < ARRAY_LENGTH; i++){ + for (i = 1; i < LONGEST_SUB_LENGTH; i++) + LONGEST_SUB[i] = TEMPORARY_ARRAY[i - 1]; + } + } + } - if(ARRAY[i] >= PIVOT){ - TEMPORARY_ARRAY_LENGTH++; - TEMPORARY_ARRAY = (int *)realloc(TEMPORARY_ARRAY, TEMPORARY_ARRAY_LENGTH*sizeof(int)); - TEMPORARY_ARRAY[TEMPORARY_ARRAY_LENGTH-1] = ARRAY[i]; - } - } + TEMPORARY_ARRAY = NULL; + TEMPORARY_ARRAY_LENGTH = 0; + for (i = 1; i < ARRAY_LENGTH; i++) + { - longestSub(TEMPORARY_ARRAY, TEMPORARY_ARRAY_LENGTH, &TEMPORARY_ARRAY, &TEMPORARY_ARRAY_LENGTH); - if(TEMPORARY_ARRAY_LENGTH + 1 > LONGEST_SUB_LENGTH){ + if (ARRAY[i] >= PIVOT) + { + TEMPORARY_ARRAY_LENGTH++; + TEMPORARY_ARRAY = (int *)realloc( + TEMPORARY_ARRAY, TEMPORARY_ARRAY_LENGTH * sizeof(int)); + TEMPORARY_ARRAY[TEMPORARY_ARRAY_LENGTH - 1] = ARRAY[i]; + } + } - LONGEST_SUB_LENGTH = TEMPORARY_ARRAY_LENGTH + 1; - LONGEST_SUB = (int *)realloc(LONGEST_SUB, LONGEST_SUB_LENGTH*sizeof(int)); - LONGEST_SUB[0] = PIVOT; - for(i = 1;i < LONGEST_SUB_LENGTH; i++) - LONGEST_SUB[i] = TEMPORARY_ARRAY[i-1]; - } - *RESULT = LONGEST_SUB; - *RESULT_LENGTH = LONGEST_SUB_LENGTH; - } - + longestSub(TEMPORARY_ARRAY, TEMPORARY_ARRAY_LENGTH, &TEMPORARY_ARRAY, + &TEMPORARY_ARRAY_LENGTH); + if (TEMPORARY_ARRAY_LENGTH + 1 > LONGEST_SUB_LENGTH) + { + LONGEST_SUB_LENGTH = TEMPORARY_ARRAY_LENGTH + 1; + LONGEST_SUB = + (int *)realloc(LONGEST_SUB, LONGEST_SUB_LENGTH * sizeof(int)); + LONGEST_SUB[0] = PIVOT; + for (i = 1; i < LONGEST_SUB_LENGTH; i++) + LONGEST_SUB[i] = TEMPORARY_ARRAY[i - 1]; + } + *RESULT = LONGEST_SUB; + *RESULT_LENGTH = LONGEST_SUB_LENGTH; + } } -int main(){ +int main() +{ - int EXAMPLE_LENGTH = 8; - int EXAMPLE[] = {18, 2, 15, 4, 30, 0, 11, 12}; - - int *RESULT = NULL; - int RESULT_LENGTH, i; - - longestSub(EXAMPLE, EXAMPLE_LENGTH, &RESULT, &RESULT_LENGTH); + int EXAMPLE_LENGTH = 8; + int EXAMPLE[] = {18, 2, 15, 4, 30, 0, 11, 12}; - printf("Longest Sub Sequence length: %d and it's:\n", RESULT_LENGTH); - for(i = 0;i < RESULT_LENGTH; i++) - printf("%d ",RESULT[i]); - printf("\n"); + int *RESULT = NULL; + int RESULT_LENGTH, i; - return 0; + longestSub(EXAMPLE, EXAMPLE_LENGTH, &RESULT, &RESULT_LENGTH); + + printf("Longest Sub Sequence length: %d and it's:\n", RESULT_LENGTH); + for (i = 0; i < RESULT_LENGTH; i++) + printf("%d ", RESULT[i]); + printf("\n"); + + return 0; } \ No newline at end of file diff --git a/misc/Prime.c b/misc/Prime.c index 9de56817..6f88b088 100644 --- a/misc/Prime.c +++ b/misc/Prime.c @@ -1,25 +1,29 @@ -#include #include +#include -int isPrime(int x) { - if (x == 2) { +int isPrime(int x) +{ + if (x == 2) + { return 1; } - if (x < 2 || x % 2 == 0) { + if (x < 2 || x % 2 == 0) + { return 0; } - + double squareRoot = sqrt(x); - - for (int i = 3; i <= squareRoot; i += 2) { + + for (int i = 3; i <= squareRoot; i += 2) + { if (x % i == 0) return 0; } return 1; - } -int main() { +int main() +{ int a; printf("Input a number to see if it is a prime number:\n"); scanf("%d", &a); diff --git a/misc/Prime_Factoriziation.c b/misc/Prime_Factoriziation.c index 15d8f192..8c18ef0f 100644 --- a/misc/Prime_Factoriziation.c +++ b/misc/Prime_Factoriziation.c @@ -1,13 +1,14 @@ /* AUTHOR: Christian Bender DATE: 12.02.2019 - DESCRIPTION: This program calculates the prime factoriziation of a positive integer > 1 + DESCRIPTION: This program calculates the prime factoriziation of a positive + integer > 1 */ +#include #include #include #include -#include /* initial length of the dynamic array */ #define LEN 10 @@ -22,10 +23,10 @@ */ typedef struct data { - int * range; + int *range; int length; } range; -typedef range* Range; +typedef range *Range; /* int_fac : calculates the prime factoriziation of positive integers */ Range int_fact(int); @@ -34,7 +35,7 @@ Range int_fact(int); void print_arr(Range); /* increase : increases the dynamic integer array */ -int * increase(int *, int); +int *increase(int *, int); /* destroy: destroys the range-structure */ void destroy(Range); @@ -57,7 +58,6 @@ int main() return 0; } - Range int_fact(int n) { assert(n > 1); /* precondition : n must be greater then 1*/ @@ -65,9 +65,9 @@ Range int_fact(int n) int len = LEN; int count = 0; int i = 0; - int * range = (int *) malloc(sizeof(int) * len); + int *range = (int *)malloc(sizeof(int) * len); assert(range); - Range pstr = (Range) malloc(sizeof(range)); + Range pstr = (Range)malloc(sizeof(range)); assert(pstr); while (n % 2 == 0) @@ -86,11 +86,10 @@ Range int_fact(int n) i++; } count++; - } int j = 3; - while (j*j <= n) + while (j * j <= n) { while (n % j == 0) { @@ -113,7 +112,6 @@ Range int_fact(int n) j += 2; } - if (n > 1) { if (i < len) @@ -134,11 +132,8 @@ Range int_fact(int n) pstr->range = range; pstr->length = count; return pstr; - - } - void print_arr(Range pStr) { assert(pStr); /* checks whether pStr is a null-pointer */ @@ -154,17 +149,15 @@ void print_arr(Range pStr) printf("\n"); } - -int * increase(int * arr, int len) +int *increase(int *arr, int len) { assert(arr); /* checks whether arr is a null-pointer */ - int * tmp = (int*) realloc(arr, sizeof(int) * (len + STEP)); + int *tmp = (int *)realloc(arr, sizeof(int) * (len + STEP)); assert(tmp); return tmp; -// assert(arr); + // assert(arr); } - void destroy(Range r) { free(r->range); diff --git a/misc/QUARTILE.c b/misc/QUARTILE.c index f9ae5cc6..d3b2d477 100644 --- a/misc/QUARTILE.c +++ b/misc/QUARTILE.c @@ -1,47 +1,47 @@ +#include #include #include -#include int main() { - int a[10], n, i, j, temp; - float q1, q3, iqr; + int a[10], n, i, j, temp; + float q1, q3, iqr; - printf("Enter no. for Random Numbers :"); - scanf("%d", &n); - for (i = 0; i < n; i++) - { - a[i] = rand() % 100; - } - printf("Random Numbers Generated are :\n"); - for (i = 0; i < n; i++) - { - printf("\n%d", a[i]); - } - printf("\n"); - printf("\nSorted Data:"); - for (i = 0; i < n; i++) - { - for (j = 0; j < n; j++) - { - if (a[i] < a[j]) - { - temp = a[i]; - a[i] = a[j]; - a[j] = temp; - } - } - } - for (i = 0; i < n; i++) - { - printf("\n%d", a[i]); - } - q1 = a[n / 4]; - printf("\nFirst Quartile : %f", q1); - q3 = a[(3 * n) / 4]; - printf("\nThird Quartile : %f", q3); - iqr = q3 - q1; - printf("\nInterQuartile Range is : %f", iqr); + printf("Enter no. for Random Numbers :"); + scanf("%d", &n); + for (i = 0; i < n; i++) + { + a[i] = rand() % 100; + } + printf("Random Numbers Generated are :\n"); + for (i = 0; i < n; i++) + { + printf("\n%d", a[i]); + } + printf("\n"); + printf("\nSorted Data:"); + for (i = 0; i < n; i++) + { + for (j = 0; j < n; j++) + { + if (a[i] < a[j]) + { + temp = a[i]; + a[i] = a[j]; + a[j] = temp; + } + } + } + for (i = 0; i < n; i++) + { + printf("\n%d", a[i]); + } + q1 = a[n / 4]; + printf("\nFirst Quartile : %f", q1); + q3 = a[(3 * n) / 4]; + printf("\nThird Quartile : %f", q3); + iqr = q3 - q1; + printf("\nInterQuartile Range is : %f", iqr); - return 0; + return 0; } \ No newline at end of file diff --git a/misc/Tower_Of_Hanoi.c b/misc/Tower_Of_Hanoi.c index 3568ccd0..59666a67 100644 --- a/misc/Tower_Of_Hanoi.c +++ b/misc/Tower_Of_Hanoi.c @@ -2,28 +2,29 @@ #include #include -// Function for Tower of Hanoi algorithm -void hanoi(int noOfDisks,char where,char to,char extra){ - if(noOfDisks == 0 ) - { - return; - } - else - { - hanoi(noOfDisks-1, where, extra , to); - printf("Move disk : %d from %c to %c\n",noOfDisks,where,to); - hanoi(noOfDisks-1,extra,to,where); - } +// Function for Tower of Hanoi algorithm +void hanoi(int noOfDisks, char where, char to, char extra) +{ + if (noOfDisks == 0) + { + return; + } + else + { + hanoi(noOfDisks - 1, where, extra, to); + printf("Move disk : %d from %c to %c\n", noOfDisks, where, to); + hanoi(noOfDisks - 1, extra, to, where); + } } -int main(void){ - int noOfDisks; - - //Asks the number of disks in the tower - printf("Number of disks: \n"); - scanf("%d", &noOfDisks); - - hanoi(noOfDisks,'A','B','C'); - - return 0; +int main(void) +{ + int noOfDisks; + // Asks the number of disks in the tower + printf("Number of disks: \n"); + scanf("%d", &noOfDisks); + + hanoi(noOfDisks, 'A', 'B', 'C'); + + return 0; } diff --git a/misc/armstrong_number.c b/misc/armstrong_number.c index ced9b9f8..66812f60 100644 --- a/misc/armstrong_number.c +++ b/misc/armstrong_number.c @@ -1,64 +1,65 @@ -//A number is called as Armstrong number if sum of cubes of digits of number is equal to the number itself. +// A number is called as Armstrong number if sum of cubes of digits of number is +// equal to the number itself. // For Example 153 is an Armstrong number because 153 = 1³+5³+3³. -#include +#include -//Function to calculate x raised to the power y -int power(int x, unsigned int y) -{ - if (y == 0) - return 1; - if (y % 2 == 0) - return power(x, y / 2) * power(x, y / 2); - return x * power(x, y / 2) * power(x, y / 2); -} +// Function to calculate x raised to the power y +int power(int x, unsigned int y) +{ + if (y == 0) + return 1; + if (y % 2 == 0) + return power(x, y / 2) * power(x, y / 2); + return x * power(x, y / 2) * power(x, y / 2); +} -//Function to calculate order of the number -int order(int x) -{ - int n = 0; - while (x) { - n++; - x = x / 10; - } - return n; -} +// Function to calculate order of the number +int order(int x) +{ + int n = 0; + while (x) + { + n++; + x = x / 10; + } + return n; +} -// Function to check whether the given number is -// Armstrong number or not -int isArmstrong(int x) -{ - // Calling order function - int n = order(x); - int temp = x, sum = 0; - while (temp) - { - int r = temp % 10; - sum += power(r, n); - temp = temp / 10; - } +// Function to check whether the given number is +// Armstrong number or not +int isArmstrong(int x) +{ + // Calling order function + int n = order(x); + int temp = x, sum = 0; + while (temp) + { + int r = temp % 10; + sum += power(r, n); + temp = temp / 10; + } - // If satisfies Armstrong condition - if (sum == x) - return 1; - else - return 0; -} + // If satisfies Armstrong condition + if (sum == x) + return 1; + else + return 0; +} // -int main() -{ - int x = 153; - if (isArmstrong(x) == 1) - printf("True\n"); - else - printf("False\n"); +int main() +{ + int x = 153; + if (isArmstrong(x) == 1) + printf("True\n"); + else + printf("False\n"); - x = 1253; - if (isArmstrong(x) == 1) - printf("True\n"); - else - printf("False\n"); - - return 0; -} + x = 1253; + if (isArmstrong(x) == 1) + printf("True\n"); + else + printf("False\n"); + return 0; +} diff --git a/misc/cantor_set.c b/misc/cantor_set.c index 78d253ef..2df3196e 100644 --- a/misc/cantor_set.c +++ b/misc/cantor_set.c @@ -4,93 +4,92 @@ struct contour { - double start; - double end; - struct contour* next; + double start; + double end; + struct contour *next; }; typedef struct contour Contour; Contour *head; void startList(double start_num, double end_num) { - if(head==NULL) - { - head = (Contour*)malloc(sizeof(Contour)); - head -> start = start_num; - head -> end = end_num; - head -> next = NULL; - } + if (head == NULL) + { + head = (Contour *)malloc(sizeof(Contour)); + head->start = start_num; + head->end = end_num; + head->next = NULL; + } } void propagate(Contour *head) { - Contour *temp = head; + Contour *temp = head; - if(temp!=NULL) - { - Contour *newNode = (Contour*)malloc(sizeof(Contour)); - double diff = ( ((temp->end)-(temp->start)) / 3); + if (temp != NULL) + { + Contour *newNode = (Contour *)malloc(sizeof(Contour)); + double diff = (((temp->end) - (temp->start)) / 3); - newNode->end = temp->end; - temp->end = ((temp->start)+diff); - newNode->start = (newNode->end)-diff; + newNode->end = temp->end; + temp->end = ((temp->start) + diff); + newNode->start = (newNode->end) - diff; - newNode->next = temp->next; + newNode->next = temp->next; - temp->next=newNode; + temp->next = newNode; - propagate(temp->next->next); - } - else - return; + propagate(temp->next->next); + } + else + return; } void print(Contour *head) { - Contour *temp = head; - while(temp!=NULL) - { - printf("\t"); - printf("[%lf] -- ", temp->start); - printf("[%lf]", temp->end); - temp=temp->next; - } - - printf("\n"); + Contour *temp = head; + while (temp != NULL) + { + printf("\t"); + printf("[%lf] -- ", temp->start); + printf("[%lf]", temp->end); + temp = temp->next; + } + printf("\n"); } int main(int argc, char const *argv[]) { - head=NULL; + head = NULL; - int start_num, end_num, levels; + int start_num, end_num, levels; - if (argc < 2) - { - printf("Enter 3 arguments: start_num \t end_num \t levels\n"); - scanf("%d %d %d", &start_num, &end_num, &levels); - } - else - { - start_num = atoi(argv[1]); - end_num = atoi(argv[2]); - levels = atoi(argv[3]); - } + if (argc < 2) + { + printf("Enter 3 arguments: start_num \t end_num \t levels\n"); + scanf("%d %d %d", &start_num, &end_num, &levels); + } + else + { + start_num = atoi(argv[1]); + end_num = atoi(argv[2]); + levels = atoi(argv[3]); + } - startList(start_num, end_num); + startList(start_num, end_num); - for (int i = 0; i < levels; i++) - { - printf("Level %d\t", i); - print(head); - propagate(head); - printf("\n"); - } - printf("Level %d\t", levels); - print(head); + for (int i = 0; i < levels; i++) + { + printf("Level %d\t", i); + print(head); + propagate(head); + printf("\n"); + } + printf("Level %d\t", levels); + print(head); - return 0; + return 0; } diff --git a/misc/cartesian_To_Polar.c b/misc/cartesian_To_Polar.c index 10638e79..8aa4b426 100644 --- a/misc/cartesian_To_Polar.c +++ b/misc/cartesian_To_Polar.c @@ -1,5 +1,5 @@ -#include #include +#include const double pi = 3.141592653589793238462643383279502884; @@ -7,38 +7,56 @@ const double pi = 3.141592653589793238462643383279502884; give as arguments to the executable two x and y coordinates outputs a polar coordinate **/ -int main() { +int main() +{ double x, y; double r, theta, thetaFinal; scanf("%lf %lf", &x, &y); r = hypot(x, y); - if (x != 0) { - if (y != 0) { - theta = atan(y / x); - if ((x > 0 && y > 0) || (x == -y)) { //Q1 - thetaFinal = theta; - } else if (x < 0 && y > 0) { //Q2 - thetaFinal = theta + pi; - } else if (x < 0 && y < 0) { //Q3 - thetaFinal = theta - pi; - } else if (x > 0 && y < 0) { //Q4 - thetaFinal = 2 * pi - theta; - } - } - } - if (x == 0) { //exceptions when no actual angle is present - if (y > 0) { - thetaFinal = pi / 2; - } else { - thetaFinal = -(pi / 2); - } - } - if (y == 0) { - if (x > 0) { - thetaFinal = 0; - } else { - thetaFinal = -pi; - } - } - printf("%.2f %.2f\n", r, atan2(y, x)); + if (x != 0) + { + if (y != 0) + { + theta = atan(y / x); + if ((x > 0 && y > 0) || (x == -y)) + { // Q1 + thetaFinal = theta; + } + else if (x < 0 && y > 0) + { // Q2 + thetaFinal = theta + pi; + } + else if (x < 0 && y < 0) + { // Q3 + thetaFinal = theta - pi; + } + else if (x > 0 && y < 0) + { // Q4 + thetaFinal = 2 * pi - theta; + } + } + } + if (x == 0) + { // exceptions when no actual angle is present + if (y > 0) + { + thetaFinal = pi / 2; + } + else + { + thetaFinal = -(pi / 2); + } + } + if (y == 0) + { + if (x > 0) + { + thetaFinal = 0; + } + else + { + thetaFinal = -pi; + } + } + printf("%.2f %.2f\n", r, atan2(y, x)); } diff --git a/misc/catalan.c b/misc/catalan.c index 6e8dde34..f985736a 100644 --- a/misc/catalan.c +++ b/misc/catalan.c @@ -1,28 +1,28 @@ /* code for computing nth catalan number */ -#include -long int factorial(int x) //long int for more than 10 factorial +#include +long int factorial(int x) // long int for more than 10 factorial { - int i; - long int fac; //fac stores x factorial - fac=x; - for(i=1;i #include diff --git a/misc/factorial_large_number.c b/misc/factorial_large_number.c index 25583890..6811abe4 100644 --- a/misc/factorial_large_number.c +++ b/misc/factorial_large_number.c @@ -90,7 +90,7 @@ int main(int argc, char *argv[]) { int number, i; - //Asks for the number/position of term in Fibonnacci sequence + // Asks for the number/position of term in Fibonnacci sequence if (argc == 2) number = atoi(argv[1]); else diff --git a/misc/factorial_trailing_zeroes.c b/misc/factorial_trailing_zeroes.c index 0ca55ede..5d92e1c3 100644 --- a/misc/factorial_trailing_zeroes.c +++ b/misc/factorial_trailing_zeroes.c @@ -1,25 +1,30 @@ /* -programme for computing number of zeroes at the end of factorial of a given number n +programme for computing number of zeroes at the end of factorial of a given +number n */ -#include -#include //including math.h header file to use pow function +#include //including math.h header file to use pow function +#include int main() { - int i,n,test=0,count=0; - //taking input number n - scanf("%d",&n); - - //looping from 1 till loop break - for(i=1;;i++) + int i, n, test = 0, count = 0; + // taking input number n + scanf("%d", &n); + + // looping from 1 till loop break + for (i = 1;; i++) { - test=n/pow(5,i);//division of n by ith power of 5(storing in integer form) - if(test!=0) //condition for zeroes at end corresponding individual ith case + test = + n / + pow(5, + i); // division of n by ith power of 5(storing in integer form) + if (test != + 0) // condition for zeroes at end corresponding individual ith case { - count=count+test; + count = count + test; } - else - break; //break the loop for if test=0 + else + break; // break the loop for if test=0 } - printf("%d\n",count); + printf("%d\n", count); return 0; } diff --git a/misc/is_Armstrong.c b/misc/is_Armstrong.c index b7955ae7..7b7f9d2f 100644 --- a/misc/is_Armstrong.c +++ b/misc/is_Armstrong.c @@ -1,24 +1,24 @@ -#include +#include int main() { - int n, sum=0, i, num; - printf("Enter number: "); - scanf("%d",&n); - num=n; - while (n!=0) - { - i=n%10; - sum=sum+(i*i*i); - n=n/10; - } - if (sum==num) - { - printf("%d is an armstrong number!\n", num); - } - else - { - printf("%d is not an armstrong number!\n", num); - } - return 0; + int n, sum = 0, i, num; + printf("Enter number: "); + scanf("%d", &n); + num = n; + while (n != 0) + { + i = n % 10; + sum = sum + (i * i * i); + n = n / 10; + } + if (sum == num) + { + printf("%d is an armstrong number!\n", num); + } + else + { + printf("%d is not an armstrong number!\n", num); + } + return 0; } diff --git a/misc/lerp.c b/misc/lerp.c index b9324ffa..0aa1ca88 100644 --- a/misc/lerp.c +++ b/misc/lerp.c @@ -1,28 +1,27 @@ -#include #include +#include -float lerp(float k0, float k1, float t) { - return k0 + t * (k1 - k0); -} +float lerp(float k0, float k1, float t) { return k0 + t * (k1 - k0); } -float lerp_precise(int k0, int k1, float t) { - return (1 - t) * k0 + t * k1; -} +float lerp_precise(int k0, int k1, float t) { return (1 - t) * k0 + t * k1; } -int main() { +int main() +{ float start = 0; - float finish = 5; - float steps = 0; - - printf("Input a number, this is the bigger bound of the lerp:\n"); + float finish = 5; + float steps = 0; + + printf("Input a number, this is the bigger bound of the lerp:\n"); scanf("%f", &finish); - printf("Input a number, this is in how many steps you want to divide the lerp:\n"); + printf("Input a number, this is in how many steps you want to divide the " + "lerp:\n"); scanf("%f", &steps); - for (int i = 0; i < steps + 1; i++) { - printf("%f\n", lerp(start, finish, i / steps)); - } + for (int i = 0; i < steps + 1; i++) + { + printf("%f\n", lerp(start, finish, i / steps)); + } return 0; } diff --git a/misc/lexicographic_Permutations.c b/misc/lexicographic_Permutations.c index f5d09cb3..e89760ff 100644 --- a/misc/lexicographic_Permutations.c +++ b/misc/lexicographic_Permutations.c @@ -1,6 +1,6 @@ #include -#include #include +#include void swap(char *left, char *right) { @@ -9,10 +9,7 @@ void swap(char *left, char *right) *right = temp; } -int compare(const void *a, const void *b) -{ - return (*(char *)a - *(char *)b); -} +int compare(const void *a, const void *b) { return (*(char *)a - *(char *)b); } void PrintSortedPermutations(char *str) { @@ -33,7 +30,8 @@ void PrintSortedPermutations(char *str) // if we couldn't find one, we're finished, else we can swap if (i >= 0) { - // 3. find character at index j such that str[j] = min(str[k]) && str[k] > str[i] for all k > i + // 3. find character at index j such that str[j] = min(str[k]) && + // str[k] > str[i] for all k > i int j = i + 1, k; for (k = j; k < strSize && str[k]; k++) { @@ -52,7 +50,7 @@ void PrintSortedPermutations(char *str) int main() { - int n; //size of string + int n; // size of string scanf("%d\n", &n); char *str = (char *)malloc(n * sizeof(char)); scanf("%s", str); diff --git a/misc/mirror.c b/misc/mirror.c index 6db82a80..4fbaa744 100644 --- a/misc/mirror.c +++ b/misc/mirror.c @@ -1,57 +1,60 @@ #include -#include // we include the library string.h to the use of string +#include // we include the library string.h to the use of string -void saisie (char *cpointeur); // Prototypes of the three functions used in the program -int compte (char *s); -char* miroir (char * s); +void saisie( + char *cpointeur); // Prototypes of the three functions used in the program +int compte(char *s); +char *miroir(char *s); -int main (int argc , char *argv[]) +int main(int argc, char *argv[]) { -char chaine[20]; -saisie(chaine); -printf("miroir est %s",miroir(chaine)); - + char chaine[20]; + saisie(chaine); + printf("miroir est %s", miroir(chaine)); } -// this function is used to put a string -void saisie (char *cpointeur) +// this function is used to put a string +void saisie(char *cpointeur) { - printf("saisir une chaine\n"); - scanf("%s",cpointeur); + printf("saisir une chaine\n"); + scanf("%s", cpointeur); } -/* the function miroir (in french ) it means "mirror" , the major idea is to permute the first caractere with the last using an auxilary -variable (aux) the the 2nd character with the penultimate one and so on . -we made a call to the function (compte) which counts the length of the string . As you can see clearly , I substruct 1 from the equation -k = compte(s)-1 ; to get rid of the EOF caractere which is '\0' because it is not a caractere from the string typed */ -char* miroir (char *s) +/* the function miroir (in french ) it means "mirror" , the major idea is to +permute the first caractere with the last using an auxilary variable (aux) the +the 2nd character with the penultimate one and so on . we made a call to the +function (compte) which counts the length of the string . As you can see clearly +, I substruct 1 from the equation k = compte(s)-1 ; to get rid of the EOF +caractere which is '\0' because it is not a caractere from the string typed */ +char *miroir(char *s) { -int i ; -char aux ; -int k ; -k = compte(s)-1 ; -i = 0 ; -while(i<=k) -{ -aux = s[i]; -s[i]=s[k]; -s[k]=aux ; -k-- ; -i++ ; + int i; + char aux; + int k; + k = compte(s) - 1; + i = 0; + while (i <= k) + { + aux = s[i]; + s[i] = s[k]; + s[k] = aux; + k--; + i++; + } + + return s; } -return s ; -} - -// compte plays the role of strlen so we can change it by an strlen function if you want that -int compte (char *s) +// compte plays the role of strlen so we can change it by an strlen function if +// you want that +int compte(char *s) { - char *p ; - int k ; - p=s ; - k=0 ; - while(*p!='\0') - { - p++ ; - k++ ; - } - return k ; + char *p; + int k; + p = s; + k = 0; + while (*p != '\0') + { + p++; + k++; + } + return k; } diff --git a/misc/palindrome.c b/misc/palindrome.c index ec82e893..2900e86e 100644 --- a/misc/palindrome.c +++ b/misc/palindrome.c @@ -8,11 +8,11 @@ int main() originalInteger = n; - // reversed integer is stored in variable - while( n!=0 ) + // reversed integer is stored in variable + while (n != 0) { - remainder = n%10; - reversedInteger = reversedInteger*10 + remainder; + remainder = n % 10; + reversedInteger = reversedInteger * 10 + remainder; n /= 10; } @@ -21,6 +21,6 @@ int main() printf("%d is a palindrome.", originalInteger); else printf("%d is not a palindrome.", originalInteger); - + return 0; } diff --git a/misc/pid.c b/misc/pid.c index 186e2d2e..44a9b361 100644 --- a/misc/pid.c +++ b/misc/pid.c @@ -1,29 +1,34 @@ /** * PID Controller - * + * * The PID controller is a linear control algorithm that has three terms: * - Proportional: A simple scaling of the error value by a gain kP - * - Integral: Integration of the error value over time, then multipled by gain kI - * - Derivative: Rate of change of the error value over time, multiplied by gain kD - * - * Terms of the controller can be removed by setting their gain to 0, creating a PI (kD = 0) - * or PD (kI = 0) controller. Depending on the control problem at hand, some terms may not - * increase the performance of the system, or may have a negative effect. - * - * For a more mathematical expanation of the PID Controller, see https://en.wikipedia.org/wiki/PID_controller - * + * - Integral: Integration of the error value over time, then multipled by gain + * kI + * - Derivative: Rate of change of the error value over time, multiplied by + * gain kD + * + * Terms of the controller can be removed by setting their gain to 0, creating a + * PI (kD = 0) or PD (kI = 0) controller. Depending on the control problem at + * hand, some terms may not increase the performance of the system, or may have + * a negative effect. + * + * For a more mathematical expanation of the PID Controller, see + * https://en.wikipedia.org/wiki/PID_controller + * * Limitations of this implementation: - * - Since this implementation is just for demonstration, the pid_step function takes the - * dt as a parameter, and it can be provided by the user in main(). This allows deterministic - * experimentation with the algorithm, rather than using time(NULL) which would make the function - * non-deterministic. - * - * Inputs: e(t) - Current error at time t. For example, how far a servo is off the desired angle - * Output: u(t) - Controller output at time t. + * - Since this implementation is just for demonstration, the pid_step function + * takes the dt as a parameter, and it can be provided by the user in main(). + * This allows deterministic experimentation with the algorithm, rather than + * using time(NULL) which would make the function non-deterministic. + * + * Inputs: e(t) - Current error at time t. For example, how far a servo is off + * the desired angle Output: u(t) - Controller output at time t. */ #include -struct pid { +struct pid +{ // Controller gains float kP; float kI; @@ -34,7 +39,8 @@ struct pid { float integral; }; -float pid_step(struct pid* controller, float dt, float error) { +float pid_step(struct pid *controller, float dt, float error) +{ // Calculate p term float p = error * controller->kP; @@ -42,33 +48,36 @@ float pid_step(struct pid* controller, float dt, float error) { controller->integral += error * dt * controller->kI; // Calculate d term, taking care to not divide by zero - float d = dt == 0 ? 0 : ((error - controller->lastError) / dt) * controller->kD; + float d = + dt == 0 ? 0 : ((error - controller->lastError) / dt) * controller->kD; controller->lastError = error; return p + controller->integral + d; } -int main() { +int main() +{ printf("PID Controller Example\n"); - struct pid controller = { - .lastError = 0, - .integral = 0 - }; + struct pid controller = {.lastError = 0, .integral = 0}; // Take the controller gains from the user - printf("Please enter controller gains in format kP, kI, KD. For example, \"1.2 2.1 3.2\"\n> "); + printf("Please enter controller gains in format kP, kI, KD. For example, " + "\"1.2 2.1 3.2\"\n> "); scanf("%f %f %f", &controller.kP, &controller.kI, &controller.kD); - printf("Using kP: %f, kI: %f, kD: %f\n", controller.kP, controller.kI, controller.kD); + printf("Using kP: %f, kI: %f, kD: %f\n", controller.kP, controller.kI, + controller.kD); - // How often the pid_step algorithm expects to be called. In a real life scenario this would - // be provided by calling time(NULL) - last_time, or by calling the function reliably at X Hz (using a timer or RTOS etc) - // For demonstration of this algorithm though, it is defined below as 1 second, allowing easy testing of integral - // and derivative terms. + // How often the pid_step algorithm expects to be called. In a real life + // scenario this would be provided by calling time(NULL) - last_time, or by + // calling the function reliably at X Hz (using a timer or RTOS etc) For + // demonstration of this algorithm though, it is defined below as 1 second, + // allowing easy testing of integral and derivative terms. float time_step = 1; float error_value; - while (1) { + while (1) + { printf("Enter error value\n>"); scanf("%f", &error_value); diff --git a/misc/strong_Number.c b/misc/strong_Number.c index baff3623..ddb0d97c 100644 --- a/misc/strong_Number.c +++ b/misc/strong_Number.c @@ -9,30 +9,30 @@ void strng(int a) { - int j = a; - int sum = 0; - int b, i, fact = 1; - while (a > 0) - { - fact = 1; - b = a % 10; - for (i = 1; i <= b; i++) - { - fact = fact * i; - } - a = a / 10; - sum = sum + fact; - } - if (sum == j) - printf("%d is a strong number", j); - else - printf("%d is not a strong number", j); + int j = a; + int sum = 0; + int b, i, fact = 1; + while (a > 0) + { + fact = 1; + b = a % 10; + for (i = 1; i <= b; i++) + { + fact = fact * i; + } + a = a / 10; + sum = sum + fact; + } + if (sum == j) + printf("%d is a strong number", j); + else + printf("%d is not a strong number", j); } int main() { - int a; - printf("Enter the number to check"); - scanf("%d", &a); - strng(a); - return 0; + int a; + printf("Enter the number to check"); + scanf("%d", &a); + strng(a); + return 0; } diff --git a/misc/sudoku_solver.c b/misc/sudoku_solver.c index 5b976210..41787c6e 100644 --- a/misc/sudoku_solver.c +++ b/misc/sudoku_solver.c @@ -1,8 +1,9 @@ -//recursion problem : Sudoku Solver -/*You are given an incomplete N*N Sudoku and asked to solve it using the following recursive algorithm: -(1) Scan the Sudoku from left to right row-wise to search for an empty cell. -(2) If there are no empty cells, print the Sudoku. Go to step 5. -(3) In the empty cell, try putting numbers 1 to N while ensuring that no two numbers in a single row, column, or box are same. Go back to step 1. +// recursion problem : Sudoku Solver +/*You are given an incomplete N*N Sudoku and asked to solve it using the +following recursive algorithm: (1) Scan the Sudoku from left to right row-wise +to search for an empty cell. (2) If there are no empty cells, print the Sudoku. +Go to step 5. (3) In the empty cell, try putting numbers 1 to N while ensuring +that no two numbers in a single row, column, or box are same. Go back to step 1. (4) Declare that the Sudoku is Invalid. (5) Exit.*/ @@ -13,81 +14,81 @@ int N, R, C; int OKrow(int a[M], int x, int y, int v) { - int j; - for (j = 0; j < N; j++) - if (a[x * N + j] == v) - return 0; - return 1; + int j; + for (j = 0; j < N; j++) + if (a[x * N + j] == v) + return 0; + return 1; } int OKcol(int a[M], int x, int y, int v) { - int i; - for (i = 0; i < N; i++) - if (a[i * N + y] == v) - return 0; - return 1; + int i; + for (i = 0; i < N; i++) + if (a[i * N + y] == v) + return 0; + return 1; } int OKbox(int a[M], int x, int y, int v) { - int bi = x / R, bj = y / C, i, j; - for (i = 0; i < R; i++) - for (j = 0; j < C; j++) - if (a[(i + bi * R) * N + (j + bj * C)] == v) - return 0; - return 1; + int bi = x / R, bj = y / C, i, j; + for (i = 0; i < R; i++) + for (j = 0; j < C; j++) + if (a[(i + bi * R) * N + (j + bj * C)] == v) + return 0; + return 1; } int OK(int a[M], int x, int y, int v) { - return OKrow(a, x, y, v) && OKcol(a, x, y, v) && OKbox(a, x, y, v); + return OKrow(a, x, y, v) && OKcol(a, x, y, v) && OKbox(a, x, y, v); } void print(int a[M]) { - int i, j; - for (i = 0; i < N; i++) - for (j = 0; j < N; j++) - printf("%d%c", a[i * N + j], (j == N - 1 ? '\n' : ' ')); + int i, j; + for (i = 0; i < N; i++) + for (j = 0; j < N; j++) + printf("%d%c", a[i * N + j], (j == N - 1 ? '\n' : ' ')); } int solve(int a[M]) { - int i, j, v, rem = 0; - for (i = 0; i < N; i++) - { - for (j = 0; j < N; j++) - { - if (a[i * N + j] == 0) - { - rem = 1; - for (v = 1; v <= N; v++) - { - if (OK(a, i, j, v)) - { - a[i * N + j] = v; - if (solve(a)) - return 1; - a[i * N + j] = 0; - } - } - } - } - } - if (rem == 0) - return 1; - return 0; + int i, j, v, rem = 0; + for (i = 0; i < N; i++) + { + for (j = 0; j < N; j++) + { + if (a[i * N + j] == 0) + { + rem = 1; + for (v = 1; v <= N; v++) + { + if (OK(a, i, j, v)) + { + a[i * N + j] = v; + if (solve(a)) + return 1; + a[i * N + j] = 0; + } + } + } + } + } + if (rem == 0) + return 1; + return 0; } int main() { - scanf("%d%d%d", &N, &R, &C); - int a[M], i, j; - for (i = 0; i < N; i++) - for (j = 0; j < N; j++) - scanf("%d", &a[i * N + j]); + scanf("%d%d%d", &N, &R, &C); + int a[M], i, j; + for (i = 0; i < N; i++) + for (j = 0; j < N; j++) + scanf("%d", &a[i * N + j]); - if (solve(a)) - print(a); - else - printf("Invalid\n"); - return 0; + if (solve(a)) + print(a); + else + printf("Invalid\n"); + return 0; } diff --git a/misc/union_Find.c b/misc/union_Find.c index 8f1c4d05..8cd11aab 100644 --- a/misc/union_Find.c +++ b/misc/union_Find.c @@ -3,23 +3,20 @@ int p[1000000]; int find(int x) { - if (p[x] == x) - { - return x; - } - else - { - p[x] = find(p[x]); - return p[x]; - } + if (p[x] == x) + { + return x; + } + else + { + p[x] = find(p[x]); + return p[x]; + } } // Call to function join(int x, int y) to join PARAM x and y -void join(int x, int y) -{ - p[find(x)] = find(y); -} +void join(int x, int y) { p[find(x)] = find(y); } -int main() +int main() { // Have all array indexes that you need to use refrence themselves for (int i = 0; i < 10; i++) @@ -34,12 +31,12 @@ int main() // Now 3, 5 and are groupped together, find(3) = find(5) = find(8) // p = {0, 1, 2, 5, 4, 8, 6, 7, 8, 9} join(0, 5); - if(find(0) == find(3)) + if (find(0) == find(3)) { printf("0 and 3 are groupped together\n"); } printf("The array is now: "); - for(int i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { printf("%d ", p[i]); } diff --git a/numerical_methods/Gauss_Elimination.c b/numerical_methods/Gauss_Elimination.c index 38f6fb31..87daa410 100644 --- a/numerical_methods/Gauss_Elimination.c +++ b/numerical_methods/Gauss_Elimination.c @@ -1,104 +1,105 @@ -#include #include +#include #define ARRAY_SIZE 20 void display(float a[ARRAY_SIZE][ARRAY_SIZE], int n) { - int i, j; - for (i = 0; i < n; i++) - { - for (j = 0; j <= n; j++) - { - printf("%.2f \t", a[i][j]); - } - printf("\n"); - } + int i, j; + for (i = 0; i < n; i++) + { + for (j = 0; j <= n; j++) + { + printf("%.2f \t", a[i][j]); + } + printf("\n"); + } } float interchange(float m[ARRAY_SIZE][ARRAY_SIZE], int i, int n) { - float tmp[ARRAY_SIZE][ARRAY_SIZE]; - float max = fabs(m[i][i]); - int j, k = i; + float tmp[ARRAY_SIZE][ARRAY_SIZE]; + float max = fabs(m[i][i]); + int j, k = i; - for (j = i; j < n; j++) - { - if (max < fabs(m[j][i])) - { - max = fabs(m[j][i]); - k = j; - } - } - for (j = 0; j <= n; j++) - { - tmp[i][j] = m[i][j]; - m[i][j] = m[k][j]; - m[k][j] = tmp[i][j]; - } - return m[ARRAY_SIZE - 1][ARRAY_SIZE - 1]; + for (j = i; j < n; j++) + { + if (max < fabs(m[j][i])) + { + max = fabs(m[j][i]); + k = j; + } + } + for (j = 0; j <= n; j++) + { + tmp[i][j] = m[i][j]; + m[i][j] = m[k][j]; + m[k][j] = tmp[i][j]; + } + return m[ARRAY_SIZE - 1][ARRAY_SIZE - 1]; } float eliminate(float m[ARRAY_SIZE][ARRAY_SIZE], int i, int n) { - float tmp; - int k = 1, l, j; - for (j = i; j < n - 1; j++) - { - tmp = -((m[i + k][i]) / (m[i][i])); - for (l = 0; l <= n; l++) - { - m[i + k][l] = (m[i + k][l]) + (m[i][l] * tmp); - } - k++; - } - return m[ARRAY_SIZE - 1][ARRAY_SIZE - 1]; + float tmp; + int k = 1, l, j; + for (j = i; j < n - 1; j++) + { + tmp = -((m[i + k][i]) / (m[i][i])); + for (l = 0; l <= n; l++) + { + m[i + k][l] = (m[i + k][l]) + (m[i][l] * tmp); + } + k++; + } + return m[ARRAY_SIZE - 1][ARRAY_SIZE - 1]; } int main(void) { - int i, j, n, k = 0, l; - float m[ARRAY_SIZE][ARRAY_SIZE], mul, tmp[ARRAY_SIZE][ARRAY_SIZE], val, ans[ARRAY_SIZE]; + int i, j, n, k = 0, l; + float m[ARRAY_SIZE][ARRAY_SIZE], mul, tmp[ARRAY_SIZE][ARRAY_SIZE], val, + ans[ARRAY_SIZE]; - printf("Total No.of Equations : "); - scanf("%d", &n); + printf("Total No.of Equations : "); + scanf("%d", &n); - printf("\n"); - for (i = 0; i < n; i++) - { + printf("\n"); + for (i = 0; i < n; i++) + { - printf("Enter Co-efficient Of Equations %d & Total --->>>\n", i + 1); - for (j = 0; j <= n; j++) - { - printf("r%d%d : ", i, j); - scanf("%f", &m[i][j]); - } - printf("\n"); - } - printf(":::::::::::: Current Matrix ::::::::::::\n\n"); - display(m, n); + printf("Enter Co-efficient Of Equations %d & Total --->>>\n", i + 1); + for (j = 0; j <= n; j++) + { + printf("r%d%d : ", i, j); + scanf("%f", &m[i][j]); + } + printf("\n"); + } + printf(":::::::::::: Current Matrix ::::::::::::\n\n"); + display(m, n); - for (i = 0; i < n - 1; i++) - { - printf("\n------->>>>>>>>>>>>>>>>>>>>>>>>-------- %d\n", i + 1); - m[ARRAY_SIZE - 1][ARRAY_SIZE - 1] = interchange(m, i, n); - display(m, n); - printf("\n_______________________________________\n"); - m[ARRAY_SIZE - 1][ARRAY_SIZE - 1] = eliminate(m, i, n); - display(m, n); - } - printf("\n\n Values are : \n"); - for (i = n - 1; i >= 0; i--) - { - l = n - 1; - mul = 0; - for (j = 0; j < k; j++) - { - mul = mul + m[i][l] * ans[l]; - l--; - } - k++; - ans[i] = (m[i][n] - mul) / m[i][i]; - printf("X%d = %.2f\n", i + 1, ans[i]); - } + for (i = 0; i < n - 1; i++) + { + printf("\n------->>>>>>>>>>>>>>>>>>>>>>>>-------- %d\n", i + 1); + m[ARRAY_SIZE - 1][ARRAY_SIZE - 1] = interchange(m, i, n); + display(m, n); + printf("\n_______________________________________\n"); + m[ARRAY_SIZE - 1][ARRAY_SIZE - 1] = eliminate(m, i, n); + display(m, n); + } + printf("\n\n Values are : \n"); + for (i = n - 1; i >= 0; i--) + { + l = n - 1; + mul = 0; + for (j = 0; j < k; j++) + { + mul = mul + m[i][l] * ans[l]; + l--; + } + k++; + ans[i] = (m[i][n] - mul) / m[i][i]; + printf("X%d = %.2f\n", i + 1, ans[i]); + } - return 0; + return 0; } diff --git a/numerical_methods/gauss_seidel_method.c b/numerical_methods/gauss_seidel_method.c index d073d879..a33d512b 100644 --- a/numerical_methods/gauss_seidel_method.c +++ b/numerical_methods/gauss_seidel_method.c @@ -1,27 +1,28 @@ -#include #include +#include int main() { - float a, b, c, a1, a2, a3, b1, b2, b3, c1, c2, c3, d1, d2, d3, x1, x2, x3; + float a, b, c, a1, a2, a3, b1, b2, b3, c1, c2, c3, d1, d2, d3, x1, x2, x3; - printf("Enter values of eq1:"); - scanf("%f%f%f%f", &a1, &a2, &a3, &d1); - printf("Enter values of eq2:"); - scanf("%f%f%f%f", &b1, &b2, &b3, &d2); - printf("Enter values of eq3:"); - scanf("%f%f%f%f", &c1, &c2, &c3, &d3); - x1 = x2 = x3 = 0.0; - do - { - a = x1; - b = x2; - c = x3; - x1 = (1 / a1) * (d1 - (a2 * x2) - (a3 * x3)); - x2 = (1 / b2) * (d2 - (b1 * x1) - (b3 * x3)); - x3 = (1 / c3) * (d3 - (c1 * x1) - (c2 * x2)); - } while (fabs(x1 - a) > 0.0001 && fabs(x2 - b) > 0.0001 && fabs(x3 - c) > 0.0001); - printf("x1=%f\nx2=%f\nx3=%f", x1, x2, x3); + printf("Enter values of eq1:"); + scanf("%f%f%f%f", &a1, &a2, &a3, &d1); + printf("Enter values of eq2:"); + scanf("%f%f%f%f", &b1, &b2, &b3, &d2); + printf("Enter values of eq3:"); + scanf("%f%f%f%f", &c1, &c2, &c3, &d3); + x1 = x2 = x3 = 0.0; + do + { + a = x1; + b = x2; + c = x3; + x1 = (1 / a1) * (d1 - (a2 * x2) - (a3 * x3)); + x2 = (1 / b2) * (d2 - (b1 * x1) - (b3 * x3)); + x3 = (1 / c3) * (d3 - (c1 * x1) - (c2 * x2)); + } while (fabs(x1 - a) > 0.0001 && fabs(x2 - b) > 0.0001 && + fabs(x3 - c) > 0.0001); + printf("x1=%f\nx2=%f\nx3=%f", x1, x2, x3); - return 0; + return 0; } \ No newline at end of file diff --git a/numerical_methods/lagrange_theorem.c b/numerical_methods/lagrange_theorem.c index 397cd9f5..b7569fd0 100644 --- a/numerical_methods/lagrange_theorem.c +++ b/numerical_methods/lagrange_theorem.c @@ -1,46 +1,46 @@ +#include #include #include -#include int main() { - float x[20], y[20], a, sum, p; - int n, i, j; + float x[20], y[20], a, sum, p; + int n, i, j; - printf("Enter the no of entry to insert->"); - scanf("%d", &n); + printf("Enter the no of entry to insert->"); + scanf("%d", &n); - for (i = 0; i < n; i++) - { - printf("enter the value of x%d->", i); - scanf("%f", &x[i]); - printf("enter the value of y%d->", i); - scanf("%f", &y[i]); - } - printf("\n X \t\t Y \n"); - printf("----------------------------\n"); - for (i = 0; i < n; i++) - { - printf("%f\t", x[i]); - printf("%f\n", y[i]); - } - printf("\nenter the value of x for interpolation:"); - scanf("%f", &a); - sum = 0; - for (i = 0; i < n; i++) - { - p = 1.0; - for (j = 0; j < n; j++) - { + for (i = 0; i < n; i++) + { + printf("enter the value of x%d->", i); + scanf("%f", &x[i]); + printf("enter the value of y%d->", i); + scanf("%f", &y[i]); + } + printf("\n X \t\t Y \n"); + printf("----------------------------\n"); + for (i = 0; i < n; i++) + { + printf("%f\t", x[i]); + printf("%f\n", y[i]); + } + printf("\nenter the value of x for interpolation:"); + scanf("%f", &a); + sum = 0; + for (i = 0; i < n; i++) + { + p = 1.0; + for (j = 0; j < n; j++) + { - if (i != j) - { - p = p * (a - x[j]) / (x[i] - x[j]); - } - sum = sum + y[i] * p; - } - printf("ans is->%f", sum); + if (i != j) + { + p = p * (a - x[j]) / (x[i] - x[j]); + } + sum = sum + y[i] * p; + } + printf("ans is->%f", sum); - return 0; - } + return 0; + } } \ No newline at end of file diff --git a/numerical_methods/mean.c b/numerical_methods/mean.c index 718abca0..63ae4b8c 100644 --- a/numerical_methods/mean.c +++ b/numerical_methods/mean.c @@ -1,41 +1,41 @@ -#include -#include -#include #include +#include +#include +#include #define MAX_LEN INT_MAX int main(int argc, char **argv) { - int *a, n = 10, i, j, temp, sum = 0; - float mean; + int *a, n = 10, i, j, temp, sum = 0; + float mean; - if (argc == 2) - { - n = atoi(argv[1]); - if (n >= MAX_LEN) - { - fprintf(stderr, "Maximum %d!\n", MAX_LEN); - return 1; - } - a = (int *)malloc(n * sizeof(int)); - } + if (argc == 2) + { + n = atoi(argv[1]); + if (n >= MAX_LEN) + { + fprintf(stderr, "Maximum %d!\n", MAX_LEN); + return 1; + } + a = (int *)malloc(n * sizeof(int)); + } - printf("Random Numbers Generated are : "); - for (i = 0; i < n; i++) - { - a[i] = rand() % 100; - printf("%2d, ", a[i]); - } - putchar('\n'); + printf("Random Numbers Generated are : "); + for (i = 0; i < n; i++) + { + a[i] = rand() % 100; + printf("%2d, ", a[i]); + } + putchar('\n'); - for (i = 0; i < n; i++) - sum = sum + a[i]; + for (i = 0; i < n; i++) + sum = sum + a[i]; - mean = sum / (float)n; - printf("\nMean :"); - printf("%f", mean); + mean = sum / (float)n; + printf("\nMean :"); + printf("%f", mean); - free(a); - return 0; + free(a); + return 0; } diff --git a/numerical_methods/median.c b/numerical_methods/median.c index ad24cdef..8bf63c24 100644 --- a/numerical_methods/median.c +++ b/numerical_methods/median.c @@ -1,51 +1,51 @@ -#include #include +#include #include int main() { - int a[10], n, i, j, temp; - float mean, median; + int a[10], n, i, j, temp; + float mean, median; - printf("Enter no. for Random Numbers :"); - scanf("%d", &n); - for (i = 0; i < n; i++) - { - a[i] = rand() % 100; - } - printf("Random Numbers Generated are :\n"); - for (i = 0; i < n; i++) - { - printf("\n%d", a[i]); - } - printf("\n"); - printf("\nSorted Data:"); - for (i = 0; i < n; i++) - { - for (j = 0; j < n; j++) - { - if (a[i] < a[j]) - { - temp = a[i]; - a[i] = a[j]; - a[j] = temp; - } - } - } - for (i = 0; i < n; i++) - { - printf("\n%d", a[i]); - } + printf("Enter no. for Random Numbers :"); + scanf("%d", &n); + for (i = 0; i < n; i++) + { + a[i] = rand() % 100; + } + printf("Random Numbers Generated are :\n"); + for (i = 0; i < n; i++) + { + printf("\n%d", a[i]); + } + printf("\n"); + printf("\nSorted Data:"); + for (i = 0; i < n; i++) + { + for (j = 0; j < n; j++) + { + if (a[i] < a[j]) + { + temp = a[i]; + a[i] = a[j]; + a[j] = temp; + } + } + } + for (i = 0; i < n; i++) + { + printf("\n%d", a[i]); + } - if (n % 2 == 0) - { - median = (a[n / 2] + a[(n / 2) - 1]) / 2; - } - else - { - median = a[n / 2]; - } - printf("\nMedian is : %f", median); + if (n % 2 == 0) + { + median = (a[n / 2] + a[(n / 2) - 1]) / 2; + } + else + { + median = a[n / 2]; + } + printf("\nMedian is : %f", median); - return 0; + return 0; } diff --git a/numerical_methods/qr_decompose.h b/numerical_methods/qr_decompose.h index 5b391fc2..a5384094 100644 --- a/numerical_methods/qr_decompose.h +++ b/numerical_methods/qr_decompose.h @@ -100,16 +100,25 @@ double *vector_sub(double *a, /**< minuend */ } /** - * Decompose matrix \f$A\f$ using [Gram-Schmidt process](https://en.wikipedia.org/wiki/QR_decomposition). + * Decompose matrix \f$A\f$ using [Gram-Schmidt + *process](https://en.wikipedia.org/wiki/QR_decomposition). * * \f{eqnarray*}{ - * \text{given that}\quad A &=& \left[\mathbf{a}_1,\mathbf{a}_2,\ldots,\mathbf{a}_{N-1},\right]\\ - * \text{where}\quad\mathbf{a}_i &=& \left[a_{0i},a_{1i},a_{2i},\ldots,a_{(M-1)i}\right]^T\quad\ldots\mbox{(column vectors)}\\ - * \text{then}\quad\mathbf{u}_i &=& \mathbf{a}_i -\sum_{j=0}^{i-1}\text{proj}_{\mathbf{u}_j}\mathbf{a}_i\\ + * \text{given that}\quad A &=& + *\left[\mathbf{a}_1,\mathbf{a}_2,\ldots,\mathbf{a}_{N-1},\right]\\ + * \text{where}\quad\mathbf{a}_i &=& + *\left[a_{0i},a_{1i},a_{2i},\ldots,a_{(M-1)i}\right]^T\quad\ldots\mbox{(column + *vectors)}\\ + * \text{then}\quad\mathbf{u}_i &=& \mathbf{a}_i + *-\sum_{j=0}^{i-1}\text{proj}_{\mathbf{u}_j}\mathbf{a}_i\\ * \mathbf{e}_i &=&\frac{\mathbf{u}_i}{\left|\mathbf{u}_i\right|}\\ - * Q &=& \begin{bmatrix}\mathbf{e}_0 & \mathbf{e}_1 & \mathbf{e}_2 & \dots & \mathbf{e}_{N-1}\end{bmatrix}\\ - * R &=& \begin{bmatrix}\langle\mathbf{e}_0\,,\mathbf{a}_0\rangle & \langle\mathbf{e}_1\,,\mathbf{a}_1\rangle & \langle\mathbf{e}_2\,,\mathbf{a}_2\rangle & \dots \\ - * 0 & \langle\mathbf{e}_1\,,\mathbf{a}_1\rangle & \langle\mathbf{e}_2\,,\mathbf{a}_2\rangle & \dots\\ + * Q &=& \begin{bmatrix}\mathbf{e}_0 & \mathbf{e}_1 & \mathbf{e}_2 & \dots & + *\mathbf{e}_{N-1}\end{bmatrix}\\ + * R &=& \begin{bmatrix}\langle\mathbf{e}_0\,,\mathbf{a}_0\rangle & + *\langle\mathbf{e}_1\,,\mathbf{a}_1\rangle & + *\langle\mathbf{e}_2\,,\mathbf{a}_2\rangle & \dots \\ + * 0 & \langle\mathbf{e}_1\,,\mathbf{a}_1\rangle & + *\langle\mathbf{e}_2\,,\mathbf{a}_2\rangle & \dots\\ * 0 & 0 & \langle\mathbf{e}_2\,,\mathbf{a}_2\rangle & \dots\\ * \vdots & \vdots & \vdots & \ddots * \end{bmatrix}\\ @@ -125,7 +134,8 @@ void qr_decompose(double **A, /**< input matrix to decompose */ double *col_vector = (double *)malloc(M * sizeof(double)); double *col_vector2 = (double *)malloc(M * sizeof(double)); double *tmp_vector = (double *)malloc(M * sizeof(double)); - for (int i = 0; i < N; i++) /* for each column => R is a square matrix of NxN */ + for (int i = 0; i < N; + i++) /* for each column => R is a square matrix of NxN */ { for (int j = 0; j < i; j++) /* second dimension of column */ R[i][j] = 0.; /* make R upper triangular */ diff --git a/numerical_methods/qr_decomposition.c b/numerical_methods/qr_decomposition.c index 0f418023..0958d20e 100644 --- a/numerical_methods/qr_decomposition.c +++ b/numerical_methods/qr_decomposition.c @@ -5,8 +5,8 @@ */ #include "qr_decompose.h" -#include #include +#include #include #include @@ -22,7 +22,8 @@ int main(void) scanf("%u %u", &ROWS, &COLUMNS); if (ROWS < COLUMNS) { - fprintf(stderr, "Number of rows must be greater than or equal to number of columns.\n"); + fprintf(stderr, "Number of rows must be greater than or equal to " + "number of columns.\n"); return -1; } diff --git a/numerical_methods/simpsons_1-3rd_rule.c b/numerical_methods/simpsons_1-3rd_rule.c index a055cc1e..7314231b 100644 --- a/numerical_methods/simpsons_1-3rd_rule.c +++ b/numerical_methods/simpsons_1-3rd_rule.c @@ -1,41 +1,42 @@ -#include #include +#include float f(float x) { - return 1.0 + x * x * x; //This is the expresion of the function to integrate? + return 1.0 + + x * x * x; // This is the expresion of the function to integrate? } int main() { - int i, n; - float a, b, h, x, s2, s3, sum, integral; + int i, n; + float a, b, h, x, s2, s3, sum, integral; - printf("enter the lower limit of the integration:"); - scanf("%f", &a); - printf("enter the upper limit of the integration:"); - scanf("%f", &b); - printf("enter the number of intervals:"); - scanf("%d", &n); + printf("enter the lower limit of the integration:"); + scanf("%f", &a); + printf("enter the upper limit of the integration:"); + scanf("%f", &b); + printf("enter the number of intervals:"); + scanf("%d", &n); - h = (b - a) / n; - sum = f(a) + f(b); - s2 = s3 = 0.0; + h = (b - a) / n; + sum = f(a) + f(b); + s2 = s3 = 0.0; - for (i = 1; i < n; i += 3) - { - x = a + i * h; - s3 = s3 + f(x) + f(x + h); - } + for (i = 1; i < n; i += 3) + { + x = a + i * h; + s3 = s3 + f(x) + f(x + h); + } - for (i = 3; i < n; i += 3) - { - x = a + i * h; - s2 = s2 + f(x); - } + for (i = 3; i < n; i += 3) + { + x = a + i * h; + s2 = s2 + f(x); + } - integral = (h / 3.0) * (sum + 2 * s2 + 4 * s3); - printf("\nValue of the integral = %9.4f\n", integral); + integral = (h / 3.0) * (sum + 2 * s2 + 4 * s3); + printf("\nValue of the integral = %9.4f\n", integral); - return 0; + return 0; } \ No newline at end of file diff --git a/numerical_methods/variance.c b/numerical_methods/variance.c index 86e42ccf..6bb8e84a 100644 --- a/numerical_methods/variance.c +++ b/numerical_methods/variance.c @@ -1,54 +1,56 @@ -#include +#include +#include #include -#include -int main() { +int main() +{ - int *ARRAY=NULL,ARRAY_LENGTH,i,TEMPORARY_ELEMENT,isSorted=0; - float MEAN=0,VARIANCE=0,STAND; + int *ARRAY = NULL, ARRAY_LENGTH, i, TEMPORARY_ELEMENT, isSorted = 0; + float MEAN = 0, VARIANCE = 0, STAND; + printf("Enter no. for Random Numbers :"); + scanf("%d", &ARRAY_LENGTH); + ARRAY = (int *)realloc( + ARRAY, + ARRAY_LENGTH * (sizeof(int))); // We allocate the dedicated memory + for (i = 0; i < ARRAY_LENGTH; i++) // We generate the random numbers + ARRAY[i] = rand() % 100; - printf("Enter no. for Random Numbers :"); - scanf("%d",&ARRAY_LENGTH); - ARRAY=(int *)realloc(ARRAY,ARRAY_LENGTH*(sizeof(int))); //We allocate the dedicated memory - for(i=0;iARRAY[i+1]){ // if the two elements aren't sorted - isSorted=0; //it means that the array is not sorted - TEMPORARY_ELEMENT=ARRAY[i]; //and we switch these elements using TEMPORARY_ELEMENT - ARRAY[i]=ARRAY[i+1]; - ARRAY[i+1]=TEMPORARY_ELEMENT; + while (!isSorted) + { // While our array's not sorted + isSorted = 1; // we suppose that it's sorted + for (i = 0; i < ARRAY_LENGTH - 1; i++) + { // then for each element of the array + if (ARRAY[i] > ARRAY[i + 1]) + { // if the two elements aren't sorted + isSorted = 0; // it means that the array is not sorted + TEMPORARY_ELEMENT = ARRAY[i]; // and we switch these elements + // using TEMPORARY_ELEMENT + ARRAY[i] = ARRAY[i + 1]; + ARRAY[i + 1] = TEMPORARY_ELEMENT; } } } - for(i=0;i -int main(){ - int t; +int main() +{ + int t; printf("Enter number of times you want to try"); - scanf("%d",&t); - while(t--) + scanf("%d", &t); + while (t--) { - unsigned long long N,p=0,sum=0; + unsigned long long N, p = 0, sum = 0; printf("Enter the value of N "); - - scanf("%lld",&N); //Take input of N from user - p = (N-1)/3; - sum = ((3*p*(p+1))/2); - p = (N-1)/5; - sum = sum + ((5*p*(p+1))/2); + scanf("%lld", &N); // Take input of N from user + p = (N - 1) / 3; + sum = ((3 * p * (p + 1)) / 2); - p = (N-1)/15; - sum = sum - ((15*p*(p+1))/2); - printf("%lld\n", sum); //print the sum of all numbers that are multiples of 3 & 5 below N + p = (N - 1) / 5; + sum = sum + ((5 * p * (p + 1)) / 2); + + p = (N - 1) / 15; + sum = sum - ((15 * p * (p + 1)) / 2); + printf("%lld\n", sum); // print the sum of all numbers that are + // multiples of 3 & 5 below N } return 0; } diff --git a/project_euler/problem_1/sol2.c b/project_euler/problem_1/sol2.c index af1fb71e..78d4585c 100644 --- a/project_euler/problem_1/sol2.c +++ b/project_euler/problem_1/sol2.c @@ -4,21 +4,23 @@ we get 3,5,6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below N. ''' ''' -This solution is based on the pattern that the successive numbers in the series follow: 0+3,+2,+1,+3,+1,+2,+3. +This solution is based on the pattern that the successive numbers in the series +follow: 0+3,+2,+1,+3,+1,+2,+3. */ #include -int main() { - int n = 0; - int sum = 0; - scanf("%d", &n); +int main() +{ + int n = 0; + int sum = 0; + scanf("%d", &n); - int terms = (n - 1) / 3; - sum += ((terms)*(6 + (terms - 1) * 3)) / 2; //sum of an A.P. - terms = (n - 1) / 5; - sum += ((terms)*(10 + (terms - 1) * 5)) / 2; - terms = (n - 1) / 15; - sum -= ((terms)*(30 + (terms - 1) * 15)) / 2; + int terms = (n - 1) / 3; + sum += ((terms) * (6 + (terms - 1) * 3)) / 2; // sum of an A.P. + terms = (n - 1) / 5; + sum += ((terms) * (10 + (terms - 1) * 5)) / 2; + terms = (n - 1) / 15; + sum -= ((terms) * (30 + (terms - 1) * 15)) / 2; - printf("%d\n", sum); + printf("%d\n", sum); } \ No newline at end of file diff --git a/project_euler/problem_1/sol3.c b/project_euler/problem_1/sol3.c index 04c12bf4..87f51a90 100644 --- a/project_euler/problem_1/sol3.c +++ b/project_euler/problem_1/sol3.c @@ -4,46 +4,49 @@ we get 3,5,6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below N. ''' ''' -This solution is based on the pattern that the successive numbers in the series follow: 0+3,+2,+1,+3,+1,+2,+3. +This solution is based on the pattern that the successive numbers in the series +follow: 0+3,+2,+1,+3,+1,+2,+3. */ #include -int main() { - int n = 0; - int sum = 0; - int num = 0; - scanf("%d", &n); - - while (1) { - num += 3; - if (num >= n) - break; - sum += num; - num += 2; - if (num >= n) - break; - sum += num; - num += 1; - if (num >= n) - break; - sum += num; - num += 3; - if (num >= n) - break; - sum += num; - num += 1; - if (num >= n) - break; - sum += num; - num += 2; - if (num >= n) - break; - sum += num; - num += 3; - if (num >= n) - break; - sum += num; - } +int main() +{ + int n = 0; + int sum = 0; + int num = 0; + scanf("%d", &n); - printf("%d\n", sum); + while (1) + { + num += 3; + if (num >= n) + break; + sum += num; + num += 2; + if (num >= n) + break; + sum += num; + num += 1; + if (num >= n) + break; + sum += num; + num += 3; + if (num >= n) + break; + sum += num; + num += 1; + if (num >= n) + break; + sum += num; + num += 2; + if (num >= n) + break; + sum += num; + num += 3; + if (num >= n) + break; + sum += num; + } + + printf("%d\n", sum); } \ No newline at end of file diff --git a/project_euler/problem_1/sol4.c b/project_euler/problem_1/sol4.c index 39989ed4..7f1fd6bb 100644 --- a/project_euler/problem_1/sol4.c +++ b/project_euler/problem_1/sol4.c @@ -1,25 +1,28 @@ -/*An Efficient code to print all the sum of all numbers that are multiples of 3 & 5 below N.*/ +/*An Efficient code to print all the sum of all numbers that are multiples of 3 + * & 5 below N.*/ #include -int main(){ - int t; +int main() +{ + int t; printf("Enter number of times you want to try"); - scanf("%d",&t); - while(t--) + scanf("%d", &t); + while (t--) { - unsigned long long N,p=0,sum=0; + unsigned long long N, p = 0, sum = 0; printf("Enter the value of N "); - - scanf("%lld",&N); //Take input of N from user - for(int i=0;i #include +#include #include char is_prime(long n) { for (long i = 2; i < sqrtl(n) + 1; i++) - if ( n % i == 0) + if (n % i == 0) return 0; return 1; } - long long sum_of_primes(long N) { - long long sum = 2; + long long sum = 2; - for (long i = 3; i < N; i+=2) /* skip even numbers */ + for (long i = 3; i < N; i += 2) /* skip even numbers */ if (is_prime(i)) sum += i; return sum; } - -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { long n = 100; - if (argc == 2) /* if command line argument is provided */ - n = atol(argv[1]); /* use that as the upper limit */ + if (argc == 2) /* if command line argument is provided */ + n = atol(argv[1]); /* use that as the upper limit */ printf("%ld: %lld\n", n, sum_of_primes(n)); diff --git a/project_euler/problem_10/sol2.c b/project_euler/problem_10/sol2.c index d746fcd7..6a484bdc 100644 --- a/project_euler/problem_10/sol2.c +++ b/project_euler/problem_10/sol2.c @@ -1,37 +1,36 @@ -#include #include +#include #include - -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { long n = 100; long long sum = 0; char *sieve = NULL; - if (argc == 2) /* if command line argument is provided */ - n = atol(argv[1]); /* use that as the upper limit */ + if (argc == 2) /* if command line argument is provided */ + n = atol(argv[1]); /* use that as the upper limit */ /* allocate memory for the sieve */ sieve = calloc(n, sizeof(*sieve)); - if(!sieve) + if (!sieve) { perror("Unable to allocate memory!"); return -1; } - /* build sieve of Eratosthenes - In the array, + /* build sieve of Eratosthenes + In the array, * if i^th cell is '1', then 'i' is composite * if i^th cell is '0', then 'i' is prime */ - for (long i = 2; i < sqrtl(n); i++) + for (long i = 2; i < sqrtl(n); i++) { /* if i^th element is prime, mark all its multiples as composites */ - if (!sieve[i]) - { - for (long j = i * i; j < n + 1; j += i) + if (!sieve[i]) + { + for (long j = i * i; j < n + 1; j += i) { sieve[j] = 1; } @@ -39,12 +38,12 @@ int main(int argc, char* argv[]) } } - for (long i = sqrtl(n)+1; i < n; i++) + for (long i = sqrtl(n) + 1; i < n; i++) if (!sieve[i]) sum += i; free(sieve); - + printf("%ld: %lld\n", n, sum); return 0; diff --git a/project_euler/problem_12/sol1.c b/project_euler/problem_12/sol1.c index 01e8438f..f0492780 100644 --- a/project_euler/problem_12/sol1.c +++ b/project_euler/problem_12/sol1.c @@ -1,6 +1,6 @@ +#include #include #include -#include long count_divisors(long long n) /* @@ -12,7 +12,7 @@ long count_divisors(long long n) */ { long num_divisors = 0; - + for (long long i = 1; i < sqrtl(n) + 1; i++) if (n % i == 0) num_divisors += 2; @@ -31,7 +31,7 @@ int main(int argc, char **argv) if (argc == 2) MAX_DIVISORS = atoi(argv[1]); - while(1) + while (1) { i++; triangle_number += i; @@ -40,7 +40,8 @@ int main(int argc, char **argv) break; } - printf("First Triangle number with more than %d divisors: %lld\n", MAX_DIVISORS, triangle_number); + printf("First Triangle number with more than %d divisors: %lld\n", + MAX_DIVISORS, triangle_number); return 0; } \ No newline at end of file diff --git a/project_euler/problem_13/sol1.c b/project_euler/problem_13/sol1.c index d64f21a4..5652d85e 100644 --- a/project_euler/problem_13/sol1.c +++ b/project_euler/problem_13/sol1.c @@ -1,5 +1,5 @@ -#include #include +#include #include #include diff --git a/project_euler/problem_14/sol1.c b/project_euler/problem_14/sol1.c index bfdcbd17..253222bd 100644 --- a/project_euler/problem_14/sol1.c +++ b/project_euler/problem_14/sol1.c @@ -30,7 +30,8 @@ int main(int argc, char **argv) long long max_len = 0, max_len_num = 0; long long MAX_NUM = 1000000; - if (argc == 2) /* set commandline argumnet as the maximum iteration number */ + if (argc == + 2) /* set commandline argumnet as the maximum iteration number */ { MAX_NUM = atoll(argv[1]); printf("Maximum number: %lld\n", MAX_NUM); @@ -41,8 +42,9 @@ int main(int argc, char **argv) * we can compute them in parallel. However, the maximum values should be * updated in synchrony so that we do not get into a "race condition". * - * To compile with supporintg gcc or clang, the flag "-fopenmp" should be passes - * while with Microsoft C compiler, the flag "/fopenmp" should be used. + * To compile with supporintg gcc or clang, the flag "-fopenmp" should be + *passes while with Microsoft C compiler, the flag "/fopenmp" should be + *used. * * Automatically detects for OPENMP using the _OPENMP macro. **/ diff --git a/project_euler/problem_15/sol1.c b/project_euler/problem_15/sol1.c index 7775a679..3c75d1ae 100644 --- a/project_euler/problem_15/sol1.c +++ b/project_euler/problem_15/sol1.c @@ -1,12 +1,11 @@ +#include #include #include -#include - /** * At every node, there are 2 possible ways to move -> down or right. - * Since it is a square grid, there are in all, 2N steps with N down - * and N right options, without preference for order. + * Since it is a square grid, there are in all, 2N steps with N down + * and N right options, without preference for order. * Hence, the path can be be traced in N out of 2N number of ways. * This is the same as binomial coeeficient. **/ @@ -18,7 +17,7 @@ unsigned long long number_of_paths(int N) path *= (N << 1) - i; path /= i + 1; } - + return path; } @@ -29,7 +28,8 @@ int main(int argc, char **argv) if (argc == 2) N = atoi(argv[1]); - printf("Number of ways to traverse diagonal of %dx%d grid = %llu\n", N, N, number_of_paths(N)); + printf("Number of ways to traverse diagonal of %dx%d grid = %llu\n", N, N, + number_of_paths(N)); return 0; } \ No newline at end of file diff --git a/project_euler/problem_16/sol1.c b/project_euler/problem_16/sol1.c index 6c307a40..17e86604 100644 --- a/project_euler/problem_16/sol1.c +++ b/project_euler/problem_16/sol1.c @@ -1,20 +1,21 @@ -#include #include -#include #include +#include +#include int main(int argc, char **argv) { const double tmp = log(10) / log(2); /* required to get number of digits */ unsigned long MAX_NUM_DIGITS; - uint8_t *digits = NULL; /* array to store individual digits. index 0 = units place */ + uint8_t *digits = + NULL; /* array to store individual digits. index 0 = units place */ int N = 1000, sum = 0; if (argc == 2) N = atoi(argv[1]); MAX_NUM_DIGITS = (N + tmp) / tmp; - + digits = calloc(MAX_NUM_DIGITS, sizeof(uint8_t)); digits[0] = 1; @@ -29,16 +30,17 @@ int main(int argc, char **argv) int carry = 0; for (int j = 0; j < MAX_NUM_DIGITS; j++) { - digits[j] = (digits[j] << 1) + carry; /* digit * 2 + carry */ + digits[j] = (digits[j] << 1) + carry; /* digit * 2 + carry */ // printf("\t value: %d\t", digits[j]); if (digits[j] > 9) { carry = 1; digits[j] -= 10; - } else + } + else carry = 0; // printf("carry: %d\t value: %d\n", carry, digits[j]); - + /* accumulate sum for last multiplication */ if (i == N - 1) sum += digits[j]; @@ -46,7 +48,7 @@ int main(int argc, char **argv) } printf("2^%d = ", N); - for(int i = MAX_NUM_DIGITS - 1; i >= 0; i--) + for (int i = MAX_NUM_DIGITS - 1; i >= 0; i--) putchar(digits[i] + 0x30); printf("\n\t Sum: %d\t Num. digits: %lu\n", sum, MAX_NUM_DIGITS); diff --git a/project_euler/problem_19/sol1.c b/project_euler/problem_19/sol1.c index 70fb7f16..0a5085df 100644 --- a/project_euler/problem_19/sol1.c +++ b/project_euler/problem_19/sol1.c @@ -1,9 +1,9 @@ #include /** - * returns number of days in a month. + * returns number of days in a month. * Month is identified by an integer - - * 0 = Jan and 11 = December + * 0 = Jan and 11 = December * For February, adjust for leap year outside the function. **/ char get_month_days(short month) @@ -16,7 +16,8 @@ char get_month_days(short month) return 30; else return 31; - } else if (month >= 7) /* odd months after July have 31 days*/ + } + else if (month >= 7) /* odd months after July have 31 days*/ { if (month & 0x01) return 31; @@ -36,36 +37,35 @@ char is_leap_year(short year) { if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) return 1; - + return 0; } #ifdef DEBUG -const char* day_string(int day) +const char *day_string(int day) { - switch(day) + switch (day) { - case 0: - return "Sunday"; - case 1: - return "Monday"; - case 2: - return "Tuesday"; - case 3: - return "Wednesday"; - case 4: - return "Thursday"; - case 5: - return "Friday"; - case 6: - return "Saturday"; - default: - return "Shouldnt see this!"; + case 0: + return "Sunday"; + case 1: + return "Monday"; + case 2: + return "Tuesday"; + case 3: + return "Wednesday"; + case 4: + return "Thursday"; + case 5: + return "Friday"; + case 6: + return "Saturday"; + default: + return "Shouldnt see this!"; } } #endif - int main(int argc, char **argv) { int count_sundays = 0; @@ -73,48 +73,51 @@ int main(int argc, char **argv) const short end_year = 2000; /** - * Let us identify days i.e., Sunday thru Saturday with integers - 0 thru 6 respectively - * Jan 1 1901 was a Tuesday + * Let us identify days i.e., Sunday thru Saturday with integers - 0 thru 6 + *respectively Jan 1 1901 was a Tuesday **/ char start_day = 2; for (int year = start_year; year <= end_year; year++) { char is_leap = is_leap_year(year); - for (char month = 0; month < 12; month ++) + for (char month = 0; month < 12; month++) { /** - * These two for-loops count the start of day for the next month. Hence, - * we have to skip the last December count */ + * These two for-loops count the start of day for the next month. + * Hence, we have to skip the last December count */ if (year == end_year && month == 11) continue; int days = get_month_days(month); - - if (is_leap && month == 1) /* for a leap year february, add a day */ - days ++; - - #ifdef DEBUG + + if (is_leap && month == 1) /* for a leap year february, add a day */ + days++; + +#ifdef DEBUG if (year == end_year) { - printf("Year: %d\t Month: %d\t Days: %d\t First of day: %s\n", year, month, days, day_string(start_day)); + printf("Year: %d\t Month: %d\t Days: %d\t First of day: %s\n", + year, month, days, day_string(start_day)); } - #endif +#endif /** Main Algorithm: - * every week has 7 days hence, the start of next day would be modulo 7 - * add to this, the current start date and ensure the result is still - * modulo 7! + * every week has 7 days hence, the start of next day would be + *modulo 7 add to this, the current start date and ensure the result + *is still modulo 7! **/ start_day = ((days % 7) + start_day) % 7; /* If start-day is a Sunday, increment counter */ if (start_day == 0) - count_sundays ++; + count_sundays++; } } - printf("Total number of Sundays that happened on the 1st of a month in the last century: %d\n", count_sundays); + printf("Total number of Sundays that happened on the 1st of a month in the " + "last century: %d\n", + count_sundays); return 0; } \ No newline at end of file diff --git a/project_euler/problem_2/so1.c b/project_euler/problem_2/so1.c index 5a902935..33745fa6 100644 --- a/project_euler/problem_2/so1.c +++ b/project_euler/problem_2/so1.c @@ -1,28 +1,30 @@ /* Problem: -Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, -the first 10 terms will be: +Each new term in the Fibonacci sequence is generated by adding the previous two +terms. By starting with 1 and 2, the first 10 terms will be: 1,2,3,5,8,13,21,34,55,89,.. -By considering the terms in the Fibonacci sequence whose values do not exceed n, find the sum of the even-valued terms. -e.g. for n=10, we have {2,8}, sum is 10. +By considering the terms in the Fibonacci sequence whose values do not exceed n, +find the sum of the even-valued terms. e.g. for n=10, we have {2,8}, sum is 10. */ #include -int main() { - int n = 0; - int sum = 0; - int i = 1; - int j = 2; - int temp; - scanf("%d", &n); +int main() +{ + int n = 0; + int sum = 0; + int i = 1; + int j = 2; + int temp; + scanf("%d", &n); - while (j <= n) { - if ((j & 1) == 0) //can also use(j%2 == 0) - sum += j; - temp = i; - i = j; - j = temp + i; - } + while (j <= n) + { + if ((j & 1) == 0) // can also use(j%2 == 0) + sum += j; + temp = i; + i = j; + j = temp + i; + } - printf("%d\n", sum); + printf("%d\n", sum); } \ No newline at end of file diff --git a/project_euler/problem_20/sol1.c b/project_euler/problem_20/sol1.c index 9464f10a..f7468b2c 100644 --- a/project_euler/problem_20/sol1.c +++ b/project_euler/problem_20/sol1.c @@ -16,7 +16,8 @@ typedef struct _big_int #ifdef DEBUG void print_digit(const big_int *my_int) { - printf("\tValue : %d\n\tNext : %p\n\tPrev : %p\n", my_int->value, my_int->next_digit, my_int->prev_digit); + printf("\tValue : %d\n\tNext : %p\n\tPrev : %p\n", my_int->value, + my_int->next_digit, my_int->prev_digit); } #endif @@ -161,9 +162,11 @@ int main(int argc, char **argv) num_digits++; } while (ptr); /* after coming to units place, there will be no valid ptr */ - printf("\nTime taken: %.4g millisecond\n", 1e3 * (end_time - start_time) / CLOCKS_PER_SEC); - printf("Digit Sum = %lu\tNumber of digits = %lu\tStorage space = %.3gkb\t \n", - sum_digits, num_digits, num_digits * sizeof(big_int) / 1024.0); + printf("\nTime taken: %.4g millisecond\n", + 1e3 * (end_time - start_time) / CLOCKS_PER_SEC); + printf( + "Digit Sum = %lu\tNumber of digits = %lu\tStorage space = %.3gkb\t \n", + sum_digits, num_digits, num_digits * sizeof(big_int) / 1024.0); remove_digits((big_int *)ptr0, -1); return 0; diff --git a/project_euler/problem_21/sol1.c b/project_euler/problem_21/sol1.c index d28308cf..98a979c7 100644 --- a/project_euler/problem_21/sol1.c +++ b/project_euler/problem_21/sol1.c @@ -90,7 +90,8 @@ int main(int argc, char **argv) clock_t end_time = clock(); - printf("\nTime taken: %.4g millisecond\n", 1e3 * (end_time - start_time) / CLOCKS_PER_SEC); + printf("\nTime taken: %.4g millisecond\n", + 1e3 * (end_time - start_time) / CLOCKS_PER_SEC); printf("Sum of all numbers = %lu\n", sum); free(flags); diff --git a/project_euler/problem_22/sol1.c b/project_euler/problem_22/sol1.c index abf456b6..17d0223e 100644 --- a/project_euler/problem_22/sol1.c +++ b/project_euler/problem_22/sol1.c @@ -26,7 +26,8 @@ void shell_sort(char data[][MAX_NAME_LEN], int LEN) char tmp_buffer[MAX_NAME_LEN]; strcpy(tmp_buffer, data[i]); - for (j = i; j >= gap && strcmp(data[j - gap], tmp_buffer) > 0; j -= gap) + for (j = i; j >= gap && strcmp(data[j - gap], tmp_buffer) > 0; + j -= gap) strcpy(data[j], data[j - gap]); strcpy(data[j], tmp_buffer); } @@ -98,14 +99,16 @@ int main(int argc, char **argv) clock_t start_time = clock(); shell_sort(names, COUNT); clock_t end_time = clock(); - printf("\nShell sort: %.4g millisecond\n", 1e3 * (end_time - start_time) / CLOCKS_PER_SEC); + printf("\nShell sort: %.4g millisecond\n", + 1e3 * (end_time - start_time) / CLOCKS_PER_SEC); } else if (method == 1) { clock_t start_time = clock(); lazy_sort(names, COUNT); clock_t end_time = clock(); - printf("\nLazy sort: %.4g millisecond\n", 1e3 * (end_time - start_time) / CLOCKS_PER_SEC); + printf("\nLazy sort: %.4g millisecond\n", + 1e3 * (end_time - start_time) / CLOCKS_PER_SEC); } long sum_score = 0; @@ -113,8 +116,7 @@ int main(int argc, char **argv) int i; #ifdef _OPENMP -#pragma omp parallel for schedule(runtime) reduction(+ \ - : sum_score) +#pragma omp parallel for schedule(runtime) reduction(+ : sum_score) #endif #ifdef DEBUG for (i = 935; i < 940; i++) @@ -125,14 +127,17 @@ int main(int argc, char **argv) unsigned int score = 0; /* score the alphabets in i^th name */ for (int j = 0; names[i][j] != '\0'; j++) - score += names[i][j] - 'A' + 1; /* convert ASCII character to integer score */ + score += names[i][j] - 'A' + + 1; /* convert ASCII character to integer score */ sum_score += score * (i + 1); #ifdef DEBUG - printf("Name: %s\tScore: %u x %u = %lu\n", names[i], score, i + 1, (unsigned long)score * (i + 1)); + printf("Name: %s\tScore: %u x %u = %lu\n", names[i], score, i + 1, + (unsigned long)score * (i + 1)); #endif } clock_t end_time = clock(); - printf("Scoring time: %.4g millisecond\n", 1e3 * (end_time - start_time) / CLOCKS_PER_SEC); + printf("Scoring time: %.4g millisecond\n", + 1e3 * (end_time - start_time) / CLOCKS_PER_SEC); printf("Total Score = %lu\n", sum_score); diff --git a/project_euler/problem_23/sol1.c b/project_euler/problem_23/sol1.c index 23e8369a..9bdc2608 100644 --- a/project_euler/problem_23/sol1.c +++ b/project_euler/problem_23/sol1.c @@ -67,7 +67,8 @@ char is_sum_of_abundant(unsigned long N) * i + j = N where both i and j should be abundant * hence we can simply check for j = N - i as we loop through i **/ - for (unsigned long i = get_next_abundant(1); i <= (N >> 1); i = get_next_abundant(i)) + for (unsigned long i = get_next_abundant(1); i <= (N >> 1); + i = get_next_abundant(i)) if (is_abundant(N - i)) { #ifdef DEBUG @@ -85,7 +86,8 @@ int main(int argc, char **argv) MAX_N = strtoul(argv[1], NULL, 10); #ifdef _OPENMP - printf("Using OpenMP parallleization with %d threads\n", omp_get_max_threads()); + printf("Using OpenMP parallleization with %d threads\n", + omp_get_max_threads()); #else printf("Not using parallleization!\n"); #endif @@ -93,8 +95,7 @@ int main(int argc, char **argv) double total_duration = 0.f; long i; #ifdef _OPENMP -#pragma omp parallel for reduction(+ \ - : sum) schedule(runtime) +#pragma omp parallel for reduction(+ : sum) schedule(runtime) #endif for (i = 1; i <= MAX_N; i++) { @@ -110,7 +111,9 @@ int main(int argc, char **argv) } printf("Time taken: %.4g s\n", total_duration); - printf("Sum of numbers that cannot be represented as sum of two abundant numbers : %lu\n", sum); + printf("Sum of numbers that cannot be represented as sum of two abundant " + "numbers : %lu\n", + sum); return 0; } diff --git a/project_euler/problem_25/sol1.c b/project_euler/problem_25/sol1.c index 75682022..6d811969 100644 --- a/project_euler/problem_25/sol1.c +++ b/project_euler/problem_25/sol1.c @@ -1,7 +1,7 @@ -#include -#include #include +#include #include +#include #include #define MAX_DIGITS 1000 @@ -10,7 +10,8 @@ * Function to add arbitraty length decimal integers stored in an array. * a + b = c = new b **/ -unsigned int add_numbers(unsigned char *a, unsigned char *b, unsigned char *c, int N) +unsigned int add_numbers(unsigned char *a, unsigned char *b, unsigned char *c, + int N) { unsigned char carry = 0; unsigned int i; @@ -71,7 +72,8 @@ unsigned int get_digits(unsigned char *number) int main(int argc, char *argv[]) { - unsigned char fn[MAX_DIGITS + 1]; /* array to store digits of a large number */ + unsigned char + fn[MAX_DIGITS + 1]; /* array to store digits of a large number */ unsigned char fn1[MAX_DIGITS + 1]; unsigned char sum[MAX_DIGITS + 1]; @@ -102,7 +104,8 @@ int main(int argc, char *argv[]) } while (digit_count < MAX_DIGITS); clock_t end_time = clock(); - printf("Time taken: %.4g ms\n", 1e3 * (end_time - start_time) / CLOCKS_PER_SEC); + printf("Time taken: %.4g ms\n", + 1e3 * (end_time - start_time) / CLOCKS_PER_SEC); printf("The nth term for %d digits: %u \n", MAX_DIGITS, index--); print_number(sum, digit_count); diff --git a/project_euler/problem_26/sol1.c b/project_euler/problem_26/sol1.c index ae0e44a2..881ff42e 100644 --- a/project_euler/problem_26/sol1.c +++ b/project_euler/problem_26/sol1.c @@ -27,7 +27,8 @@ int main(int argc, char *argv[]) { unsigned short remainders[MAX_LEN]; unsigned short rem = 1, *rem_ptr = remainders; - memset(remainders, (unsigned short)-1, MAX_LEN * sizeof(unsigned short)); + memset(remainders, (unsigned short)-1, + MAX_LEN * sizeof(unsigned short)); // remainders[0] = 1; // printf("1/%-4u\t ", deno); unsigned short index = 0, num_digits; @@ -40,7 +41,8 @@ int main(int argc, char *argv[]) index = 0; break; } - rem_ptr = (unsigned short *)bsearch(&rem, remainders, MAX_LEN, sizeof(unsigned short), compare); + rem_ptr = (unsigned short *)bsearch( + &rem, remainders, MAX_LEN, sizeof(unsigned short), compare); // printf("%2d, ", rem); // printf("(%14p), ", rem_ptr); if (rem_ptr != NULL) @@ -51,7 +53,8 @@ int main(int argc, char *argv[]) } num_digits = index - (rem_ptr - remainders); - // printf("\n\t(%14p, %14p, %4u, %4u)\n", rem_ptr, remainders, index, num_digits); + // printf("\n\t(%14p, %14p, %4u, %4u)\n", rem_ptr, remainders, index, + // num_digits); #ifdef _OPENMP #pragma omp critical { @@ -68,8 +71,10 @@ int main(int argc, char *argv[]) } clock_t end_time = clock(); - printf("Time taken: %.4g ms\n", 1e3 * (double)(end_time - start_time) / CLOCKS_PER_SEC); - printf("Maximum digits: %hu\t Denominator: %hu\n", max_digits, max_idx_number); + printf("Time taken: %.4g ms\n", + 1e3 * (double)(end_time - start_time) / CLOCKS_PER_SEC); + printf("Maximum digits: %hu\t Denominator: %hu\n", max_digits, + max_idx_number); return 0; } diff --git a/project_euler/problem_3/sol1.c b/project_euler/problem_3/sol1.c index 680b2882..8fd37cba 100644 --- a/project_euler/problem_3/sol1.c +++ b/project_euler/problem_3/sol1.c @@ -1,71 +1,72 @@ /* Problem: -The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factor of a given number N? -e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17. +The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factor +of a given number N? e.g. for 10, largest prime factor = 5. For 17, largest +prime factor = 17. */ -#include #include +#include int isprime(int no) { - int sq; + int sq; - if (no == 2) - { - return 1; - } - else if (no % 2 == 0) - { - return 0; - } - sq = ((int)(sqrt(no))) + 1; - for (int i = 3; i < sq; i += 2) - { - if (no % i == 0) - { - return 0; - } - } - return 1; + if (no == 2) + { + return 1; + } + else if (no % 2 == 0) + { + return 0; + } + sq = ((int)(sqrt(no))) + 1; + for (int i = 3; i < sq; i += 2) + { + if (no % i == 0) + { + return 0; + } + } + return 1; } int main() { - int maxNumber = 0; - int n = 0; - int n1; - scanf("%d", &n); - if (isprime(n) == 1) - printf("%d", n); - else - { - while (n % 2 == 0) - { - n = n / 2; - } - if (isprime(n) == 1) - { - printf("%d\n", n); - } - else - { - n1 = ((int)(sqrt(n))) + 1; - for (int i = 3; i < n1; i += 2) - { - if (n % i == 0) - { - if (isprime((int)(n / i)) == 1) - { - maxNumber = n / i; - break; - } - else if (isprime(i) == 1) - { - maxNumber = i; - } - } - } - printf("%d\n", maxNumber); - } - } + int maxNumber = 0; + int n = 0; + int n1; + scanf("%d", &n); + if (isprime(n) == 1) + printf("%d", n); + else + { + while (n % 2 == 0) + { + n = n / 2; + } + if (isprime(n) == 1) + { + printf("%d\n", n); + } + else + { + n1 = ((int)(sqrt(n))) + 1; + for (int i = 3; i < n1; i += 2) + { + if (n % i == 0) + { + if (isprime((int)(n / i)) == 1) + { + maxNumber = n / i; + break; + } + else if (isprime(i) == 1) + { + maxNumber = i; + } + } + } + printf("%d\n", maxNumber); + } + } } \ No newline at end of file diff --git a/project_euler/problem_3/sol2.c b/project_euler/problem_3/sol2.c index d8ccd4ce..f9cce337 100644 --- a/project_euler/problem_3/sol2.c +++ b/project_euler/problem_3/sol2.c @@ -1,23 +1,27 @@ /* Problem: -The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factor of a given number N? -e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17. +The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factor +of a given number N? e.g. for 10, largest prime factor = 5. For 17, largest +prime factor = 17. */ #include -int main() { - int n = 0; - scanf("%d", &n); - int prime = 1; - int i = 2; - while (i*i <= n) { - while (n%i == 0) { - prime = i; - n /= i; - } - i += 1; - } - if (n > 1) - prime = n; - printf("%d\n", prime); +int main() +{ + int n = 0; + scanf("%d", &n); + int prime = 1; + int i = 2; + while (i * i <= n) + { + while (n % i == 0) + { + prime = i; + n /= i; + } + i += 1; + } + if (n > 1) + prime = n; + printf("%d\n", prime); } \ No newline at end of file diff --git a/project_euler/problem_4/sol.c b/project_euler/problem_4/sol.c index 0a6b4c33..ba5677a8 100644 --- a/project_euler/problem_4/sol.c +++ b/project_euler/problem_4/sol.c @@ -4,7 +4,7 @@ int is_palindromic(unsigned int n) { unsigned int reversed = 0, t = n; - while (t>0) + while (t > 0) { reversed = 10 * reversed + (t % 10); t /= 10; diff --git a/project_euler/problem_401/sol1.c b/project_euler/problem_401/sol1.c index 2a62dbc9..3e090a9b 100644 --- a/project_euler/problem_401/sol1.c +++ b/project_euler/problem_401/sol1.c @@ -1,7 +1,7 @@ -#include -#include -#include #include +#include +#include +#include #define __STDC_FORMAT_MACROS #include #ifdef _OPENMP @@ -85,8 +85,7 @@ uint64_t sigma(uint64_t N) int64_t i; #ifdef _OPENMP -#pragma omp parallel for reduction(+ \ - : sum) +#pragma omp parallel for reduction(+ : sum) #endif for (i = 0; i <= N; i++) { diff --git a/project_euler/problem_6/sol.c b/project_euler/problem_6/sol.c index 1c7f7dd2..3dd68bd9 100644 --- a/project_euler/problem_6/sol.c +++ b/project_euler/problem_6/sol.c @@ -1,8 +1,10 @@ #include -int main(void) { +int main(void) +{ unsigned s1 = 0, s2 = 0, i; - for (i = 1; i <= 100; i++) { + for (i = 1; i <= 100; i++) + { s1 += i * i; s2 += i; } diff --git a/project_euler/problem_7/sol.c b/project_euler/problem_7/sol.c index e7dcae2c..72cc6622 100644 --- a/project_euler/problem_7/sol.c +++ b/project_euler/problem_7/sol.c @@ -1,7 +1,8 @@ #include #include -int main(void) { +int main(void) +{ char *sieve; size_t i; unsigned count = 0; @@ -9,15 +10,19 @@ int main(void) { const unsigned target = 10001; sieve = calloc(n, sizeof *sieve); - for (i = 2; i < n; i++) { - if (!sieve[i]) { - size_t j; + for (i = 2; i < n; i++) + { + if (!sieve[i]) + { + size_t j; count++; - if (count == target) { + if (count == target) + { printf("%lu\n", i); break; } - for (j = i * 2; j < n; j += i) { + for (j = i * 2; j < n; j += i) + { sieve[j] = 1; } } diff --git a/project_euler/problem_8/sol1.c b/project_euler/problem_8/sol1.c index 2615648b..c5ce9911 100644 --- a/project_euler/problem_8/sol1.c +++ b/project_euler/problem_8/sol1.c @@ -3,10 +3,11 @@ long long int get_product(FILE *fp, long start_pos, int num_digits) { - char ch = ' '; /* temporary variable to store character read from file */ + char ch = ' '; /* temporary variable to store character read from file */ unsigned char num = 0; /* temporary variable to store digit read */ long long int prod = 1; /* product accumulator */ - int count = 0; /* we use this variable to count number of bytes of file read */ + int count = + 0; /* we use this variable to count number of bytes of file read */ /* accumulate product for num_digits */ for (int i = 0; i < num_digits; i++, count++) @@ -29,8 +30,9 @@ long long int get_product(FILE *fp, long start_pos, int num_digits) if (num == 0) { /* If number is zero, we can skip the next 'num_digits' - * because this '0' will repeat in the next 'num_digit' multiplications. - * Hence, we also do not update the file position */ + * because this '0' will repeat in the next 'num_digit' + * multiplications. Hence, we also do not update the file position + */ /* NOTE: this is not needed but helps get results faster :) */ return 0; } @@ -78,8 +80,10 @@ int main(int argc, char *argv[]) } } while (!feof(fp)); /* loop till end of file is reached */ - printf("Maximum product: %lld\t Location: %d^th position\n\t", max_prod, position); - fseek(fp, position, SEEK_SET); /* move cursor to identified position in file */ + printf("Maximum product: %lld\t Location: %d^th position\n\t", max_prod, + position); + fseek(fp, position, + SEEK_SET); /* move cursor to identified position in file */ /* loop through all digits */ for (; num_digits > 0; num_digits--) { diff --git a/project_euler/problem_8/sol2.c b/project_euler/problem_8/sol2.c index 5a9e2155..6e768fc9 100644 --- a/project_euler/problem_8/sol2.c +++ b/project_euler/problem_8/sol2.c @@ -46,7 +46,8 @@ int main(int argc, char *argv[]) */ if (ch < 0x30 || ch > 0x39) { - num_bad_chars++; /* this is used to get the bad characters in the sequence of 13 characters */ + num_bad_chars++; /* this is used to get the bad characters in the + sequence of 13 characters */ continue; } else if (num_bad_chars > 0) @@ -68,8 +69,9 @@ int main(int argc, char *argv[]) if (num_prev != 0) { - /* since product is accumulated, the new product can be obtained by simply - * multiplying the new digit and dividing with the oldest digit + /* since product is accumulated, the new product can be obtained by + * simply multiplying the new digit and dividing with the oldest + * digit */ prod /= num_prev; /* divide first to avoid over-flows */ prod *= num; @@ -96,8 +98,10 @@ int main(int argc, char *argv[]) } } while (!feof(fp)); /* loop till end of file is reached */ - printf("Maximum product: %lld\t Location: %d^th position\n\t", max_prod, position); - fseek(fp, position, SEEK_SET); /* move cursor to identified position in file */ + printf("Maximum product: %lld\t Location: %d^th position\n\t", max_prod, + position); + fseek(fp, position, + SEEK_SET); /* move cursor to identified position in file */ /* loop through all digits */ for (; num_digits > 0; num_digits--) { diff --git a/project_euler/problem_9/sol1.c b/project_euler/problem_9/sol1.c index 1893425c..c3b3d421 100644 --- a/project_euler/problem_9/sol1.c +++ b/project_euler/problem_9/sol1.c @@ -3,13 +3,14 @@ int main(void) { for (int a = 1; a < 300; a++) - for (int b = a+1; b < 400; b++) - for (int c = b+1; c < 500; c++) + for (int b = a + 1; b < 400; b++) + for (int c = b + 1; c < 500; c++) { if (a * a + b * b == c * c) if (a + b + c == 1000) { - printf("%d x %d x %d = %ld\n", a, b, c, (long int) a*b*c); + printf("%d x %d x %d = %ld\n", a, b, c, + (long int)a * b * c); return 0; } } diff --git a/project_euler/problem_9/sol2.c b/project_euler/problem_9/sol2.c index fc52c588..976655de 100644 --- a/project_euler/problem_9/sol2.c +++ b/project_euler/problem_9/sol2.c @@ -3,11 +3,10 @@ /** Problem Statement: - A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, - a^2 + b^2 = c^2 - For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. - There exists exactly one Pythagorean triplet for which a + b + c = 1000. - Find the product abc. + A Pythagorean triplet is a set of three natural numbers, a < b < c, for + which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists + exactly one Pythagorean triplet for which a + b + c = 1000. Find the product + abc. Given a^2 + b^2 = c^2 and a+b+c = n, we can write: @@ -29,7 +28,7 @@ int main(void) if (a * a + b * b == c * c) { - printf("%d x %d x %d = %ld\n", a, b, c, (long int) a*b*c); + printf("%d x %d x %d = %ld\n", a, b, c, (long int)a * b * c); return 0; } } diff --git a/searching/Binary_Search.c b/searching/Binary_Search.c index 9fa0dc2d..78a4cf88 100644 --- a/searching/Binary_Search.c +++ b/searching/Binary_Search.c @@ -1,39 +1,42 @@ #include -// Recursive Function- It returns location of x assumiung array arr[l..r] is present, otherwise -1 +// Recursive Function- It returns location of x assumiung array arr[l..r] is +// present, otherwise -1 int binarysearch(int arr[], int l, int r, int x) { - if (r >= l) - { - int mid = l + (r - l)/2; + if (r >= l) + { + int mid = l + (r - l) / 2; // If element is present at middle - if (arr[mid] == x) return mid; + if (arr[mid] == x) + return mid; // If element is smaller than middle - if (arr[mid] > x) return binarysearch(arr, l, mid-1, x); + if (arr[mid] > x) + return binarysearch(arr, l, mid - 1, x); // Else element is in right subarray - return binarysearch(arr, mid+1, r, x); - } + return binarysearch(arr, mid + 1, r, x); + } - // When element is not present in array - return -1; + // When element is not present in array + return -1; } int main(void) { - // give function an array to work with - int arr[] = {2, 3, 4, 10, 40}; - // get size of array - int n = sizeof(arr)/ sizeof(arr[0]); - //set value to look for - int x = 10; - // set result to what is returned from binarysearch - int result = binarysearch(arr, 0, n-1, x); - // print out result - (result == -1) ? printf("Element is not in the array\n") - : printf("Element is present at index %d\n", result); - return 0; + // give function an array to work with + int arr[] = {2, 3, 4, 10, 40}; + // get size of array + int n = sizeof(arr) / sizeof(arr[0]); + // set value to look for + int x = 10; + // set result to what is returned from binarysearch + int result = binarysearch(arr, 0, n - 1, x); + // print out result + (result == -1) ? printf("Element is not in the array\n") + : printf("Element is present at index %d\n", result); + return 0; } diff --git a/searching/Jump_Search.c b/searching/Jump_Search.c index 0afb8b77..80c9ab9c 100644 --- a/searching/Jump_Search.c +++ b/searching/Jump_Search.c @@ -1,33 +1,37 @@ -#include #include -#define min(X,Y) ((X) < (Y) ? (X) : (Y)) -int jump_search(int* arr, int x); +#include +#define min(X, Y) ((X) < (Y) ? (X) : (Y)) +int jump_search(int *arr, int x); int n; -int main() { - int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610 }; - n = sizeof(arr) / sizeof(int); - int x = 55; - int index = jump_search(arr, x); - printf("\nNumber %d is at index %d\n", x, index); +int main() +{ + int arr[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610}; + n = sizeof(arr) / sizeof(int); + int x = 55; + int index = jump_search(arr, x); + printf("\nNumber %d is at index %d\n", x, index); } -int jump_search(int* arr, int x) { - int step = floor(sqrt(n)); - int prev = 0; - while (*(arr + (min(step, n) - 1)) < x) { - prev = step; - step += floor(sqrt(n)); - if (prev >= n) - return -1; - } +int jump_search(int *arr, int x) +{ + int step = floor(sqrt(n)); + int prev = 0; + while (*(arr + (min(step, n) - 1)) < x) + { + prev = step; + step += floor(sqrt(n)); + if (prev >= n) + return -1; + } - while (*(arr + prev) < x) { - prev = prev + 1; - if (prev == fmin(step, n)) - return -1; - } - if (*(arr + prev) == x) - return prev; - return -1; + while (*(arr + prev) < x) + { + prev = prev + 1; + if (prev == fmin(step, n)) + return -1; + } + if (*(arr + prev) == x) + return prev; + return -1; } diff --git a/searching/Linear_Search.c b/searching/Linear_Search.c index 3ee72471..aa9b27c8 100644 --- a/searching/Linear_Search.c +++ b/searching/Linear_Search.c @@ -3,33 +3,34 @@ int linearsearch(int *arr, int size, int val) { - int i; - for (i = 0; i < size; i++) - { - if (arr[i] == val) - return 1; - } - return 0; + int i; + for (i = 0; i < size; i++) + { + if (arr[i] == val) + return 1; + } + return 0; } int main() { - int n, i, v; - printf("Enter the size of the array:\n"); - scanf("%d", &n); //Taking input for the size of Array + int n, i, v; + printf("Enter the size of the array:\n"); + scanf("%d", &n); // Taking input for the size of Array - int *a = (int *)malloc(n * sizeof(int)); - printf("Enter the contents for an array of size %d:\n", n); - for (i = 0; i < n; i++) - scanf("%d", &a[i]); // accepts the values of array elements until the loop terminates// + int *a = (int *)malloc(n * sizeof(int)); + printf("Enter the contents for an array of size %d:\n", n); + for (i = 0; i < n; i++) + scanf("%d", &a[i]); // accepts the values of array elements until the + // loop terminates// - printf("Enter the value to be searched:\n"); - scanf("%d", &v); //Taking input the value to be searched - if (linearsearch(a, n, v)) - printf("Value %d is in the array.\n", v); - else - printf("Value %d is not in the array.\n", v); + printf("Enter the value to be searched:\n"); + scanf("%d", &v); // Taking input the value to be searched + if (linearsearch(a, n, v)) + printf("Value %d is in the array.\n", v); + else + printf("Value %d is not in the array.\n", v); - free(a); - return 0; + free(a); + return 0; } diff --git a/searching/Other_Binary_Search.c b/searching/Other_Binary_Search.c index 85a65099..5d75a95b 100644 --- a/searching/Other_Binary_Search.c +++ b/searching/Other_Binary_Search.c @@ -4,43 +4,43 @@ int binarySearch(int array[], int leng, int searchX) { - int pos = -1, right, left, i = 0; + int pos = -1, right, left, i = 0; - left = 0; - right = leng - 1; + left = 0; + right = leng - 1; - while (left <= right) - { - pos = left + (right - left) / 2; - if (array[pos] == searchX) - { - return pos; - } - else if (array[pos] > searchX) - { - right = pos - 1; - } - else - { - left = pos + 1; - } - } - return -1; /* not found */ + while (left <= right) + { + pos = left + (right - left) / 2; + if (array[pos] == searchX) + { + return pos; + } + else if (array[pos] > searchX) + { + right = pos - 1; + } + else + { + left = pos + 1; + } + } + return -1; /* not found */ } int main(int argc, char *argv[]) { - int array[len] = {5, 8, 10, 14, 16}; + int array[len] = {5, 8, 10, 14, 16}; - int position; - position = binarySearch(array, len, 5); + int position; + position = binarySearch(array, len, 5); - if (position < 0) - printf("The number %d doesnt exist in array\n", 5); - else - { - printf("The number %d exist in array at position : %d \n", 5, position); - } + if (position < 0) + printf("The number %d doesnt exist in array\n", 5); + else + { + printf("The number %d exist in array at position : %d \n", 5, position); + } - return 0; + return 0; } diff --git a/searching/fibonacci_Search.c b/searching/fibonacci_Search.c index 35f63b98..9bffb7d4 100644 --- a/searching/fibonacci_Search.c +++ b/searching/fibonacci_Search.c @@ -4,9 +4,9 @@ int fibMonaccianSearch(int arr[], int x, int n) { /* Initialize fibonacci numbers */ - int fibMMm2 = 0; // (m-2)'th Fibonacci No. - int fibMMm1 = 1; // (m-1)'th Fibonacci No. - int fibM = fibMMm2 + fibMMm1; // m'th Fibonacci + int fibMMm2 = 0; // (m-2)'th Fibonacci No. + int fibMMm1 = 1; // (m-1)'th Fibonacci No. + int fibM = fibMMm2 + fibMMm1; // m'th Fibonacci /* fibM is going to store the smallest Fibonacci Number greater than or equal to n */ @@ -14,7 +14,7 @@ int fibMonaccianSearch(int arr[], int x, int n) { fibMMm2 = fibMMm1; fibMMm1 = fibM; - fibM = fibMMm2 + fibMMm1; + fibM = fibMMm2 + fibMMm1; } // Marks the eliminated range from front @@ -28,13 +28,13 @@ int fibMonaccianSearch(int arr[], int x, int n) // Check if fibMm2 is a valid location // sets i to the min. of (offset+fibMMm2) and (n-1) - int i = ((offset+fibMMm2) < (n-1)) ? (offset+fibMMm2) : (n-1); + int i = ((offset + fibMMm2) < (n - 1)) ? (offset + fibMMm2) : (n - 1); /* If x is greater than the value at index fibMm2, cut the subarray array from offset to i */ if (arr[i] < x) { - fibM = fibMMm1; + fibM = fibMMm1; fibMMm1 = fibMMm2; fibMMm2 = fibM - fibMMm1; offset = i; @@ -44,30 +44,29 @@ int fibMonaccianSearch(int arr[], int x, int n) cut the subarray after i+1 */ else if (arr[i] > x) { - fibM = fibMMm2; + fibM = fibMMm2; fibMMm1 = fibMMm1 - fibMMm2; fibMMm2 = fibM - fibMMm1; } /* element found. return index */ - else return i; + else + return i; } /* comparing the last element with x */ - if(fibMMm1 && arr[offset+1]==x)return offset+1; + if (fibMMm1 && arr[offset + 1] == x) + return offset + 1; /*element not found. return -1 */ return -1; } - int main(void) { - int arr[] = {10, 22, 35, 40, 45, 50, 80, 82, - 85, 90, 100}; - int n = sizeof(arr)/sizeof(arr[0]); + int arr[] = {10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100}; + int n = sizeof(arr) / sizeof(arr[0]); int x = 85; - printf("Found at index: %d", - fibMonaccianSearch(arr, x, n)); + printf("Found at index: %d", fibMonaccianSearch(arr, x, n)); return 0; } diff --git a/searching/interpolation_search.c b/searching/interpolation_search.c index c965bc8d..473eaac7 100644 --- a/searching/interpolation_search.c +++ b/searching/interpolation_search.c @@ -1,22 +1,27 @@ -#include +#include /* By comparison, binary search always chooses the middle of the remaining * search space, discarding one half or the other, depending on the comparison - * between the key found at the estimated position and the key sought. The remaining - * search space is reduced to the part before or after the estimated position. - * The linear search uses equality only as it compares elements one-by-one from the start, ignoring any sorting. - * On average the interpolation search makes about log(log(n)) comparisons (if the elements - * are uniformly distributed), where n is the number of elements to be searched. In the worst case - * (for instance where the numerical values of the keys increase exponentially) it can make up to O(n) comparisons. - * In interpolation-sequential search, interpolation is used to find an item near the one being searched for, - * then linear search is used to find the exact item. */ + * between the key found at the estimated position and the key sought. The + * remaining search space is reduced to the part before or after the estimated + * position. The linear search uses equality only as it compares elements + * one-by-one from the start, ignoring any sorting. On average the interpolation + * search makes about log(log(n)) comparisons (if the elements are uniformly + * distributed), where n is the number of elements to be searched. In the worst + * case (for instance where the numerical values of the keys increase + * exponentially) it can make up to O(n) comparisons. In + * interpolation-sequential search, interpolation is used to find an item near + * the one being searched for, then linear search is used to find the exact + * item. */ int interpolationSearch(int arr[], int n, int key) { int low = 0, high = n - 1; - while (low <= high && key >= arr[low] && key <= arr[high]) { + while (low <= high && key >= arr[low] && key <= arr[high]) + { /* Calculate the nearest posible position of key */ - int pos = low + ((key - arr[low]) * (high - low)) / (arr[high] - arr[low]); + int pos = + low + ((key - arr[low]) * (high - low)) / (arr[high] - arr[low]); if (key > arr[pos]) low = pos + 1; else if (key < arr[pos]) @@ -28,19 +33,17 @@ int interpolationSearch(int arr[], int n, int key) return -1; } - int main() { int x; - int arr[] = {10, 12, 13, 16, 18, 19, 20, 21, 22, 23, - 24, 33, 35, 42, 47}; - int n = sizeof(arr)/sizeof(arr[0]); + int arr[] = {10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47}; + int n = sizeof(arr) / sizeof(arr[0]); printf("Array: "); - for(int i = 0; i < n; i++) + for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\nEnter the number to be searched: "); - scanf("%d",&x); /* Element to be searched */ + scanf("%d", &x); /* Element to be searched */ int index = interpolationSearch(arr, n, x); diff --git a/searching/modified_Binary_Search.c b/searching/modified_Binary_Search.c index 5dcd00f1..3ddb834a 100644 --- a/searching/modified_Binary_Search.c +++ b/searching/modified_Binary_Search.c @@ -1,7 +1,7 @@ #include #include -int n, m; //size of the matrix +int n, m; // size of the matrix // This function does Binary search for x in i-th row from j_low to j_high. void binarySearch(int **mat, int i, int j_low, int j_high, int x) @@ -25,8 +25,8 @@ void binarySearch(int **mat, int i, int j_low, int j_high, int x) printf("element not found\n"); } -// Function to perform binary search on the mid values of row to get the desired pair of rows -// where the element can be found +// Function to perform binary search on the mid values of row to get the desired +// pair of rows where the element can be found void modifiedBinarySearch(int **mat, int n, int m, int x) { // If Single row matrix if (n == 1) @@ -77,7 +77,7 @@ void modifiedBinarySearch(int **mat, int n, int m, int x) int main() { - int x; //element to be searched + int x; // element to be searched scanf("%d %d %d\n", &n, &m, &x); int **mat = (int **)malloc(n * sizeof(int *)); for (x = 0; x < n; x++) diff --git a/searching/pattern_search/boyer_moore_search.c b/searching/pattern_search/boyer_moore_search.c index 9d719901..87ed5879 100644 --- a/searching/pattern_search/boyer_moore_search.c +++ b/searching/pattern_search/boyer_moore_search.c @@ -3,17 +3,17 @@ #define NUM_OF_CHARS 256 -int max(int a, int b) {return (a>b)? a:b;} +int max(int a, int b) { return (a > b) ? a : b; } void computeArray(char *pattern, int size, int arr[NUM_OF_CHARS]) { int i; - for(i = 0; i < NUM_OF_CHARS; i++) + for (i = 0; i < NUM_OF_CHARS; i++) arr[i] = -1; /* Fill the actual value of last occurrence of a character */ - for(i = 0; i < size; i++) - arr[(int) pattern[i]] = i; + for (i = 0; i < size; i++) + arr[(int)pattern[i]] = i; } /* Boyer Moore Search algorithm */ void boyer_moore_search(char *str, char *pattern) @@ -24,7 +24,7 @@ void boyer_moore_search(char *str, char *pattern) int arr[NUM_OF_CHARS]; computeArray(pattern, m, arr); - while(shift <= (n - m)) + while (shift <= (n - m)) { int j = m - 1; while (j >= 0 && pattern[j] == str[shift + j]) @@ -33,8 +33,10 @@ void boyer_moore_search(char *str, char *pattern) { printf("--Pattern is found at: %d\n", shift); shift += (shift + m < n) ? m - arr[str[shift + m]] : 1; - } else { - shift += max(1, j - arr[str[shift +j]]); + } + else + { + shift += max(1, j - arr[str[shift + j]]); } } } diff --git a/searching/ternary_search.c b/searching/ternary_search.c index 00d52683..0447a4cb 100644 --- a/searching/ternary_search.c +++ b/searching/ternary_search.c @@ -1,83 +1,89 @@ - -#include - -// Function to perform Ternary Search -int ternarySearch(int l, int r, int key, int ar[]) -{ - if (r >= l) { - - // Find the mid1 and mid2 - int mid1 = l + (r - l) / 3; - int mid2 = r - (r - l) / 3; - - // Check if key is present at any mid - if (ar[mid1] == key) { - return mid1; - } - if (ar[mid2] == key) { - return mid2; - } - - // Since key is not present at mid, - // check in which region it is present - // then repeat the Search operation - // in that region - - if (key < ar[mid1]) { - - // The key lies in between l and mid1 - return ternarySearch(l, mid1 - 1, key, ar); - } - else if (key > ar[mid2]) { - - // The key lies in between mid2 and r - return ternarySearch(mid2 + 1, r, key, ar); - } - else { - - // The key lies in between mid1 and mid2 - return ternarySearch(mid1 + 1, mid2 - 1, key, ar); - } - } - - // Key not found - return -1; -} - -// Driver code -int main() -{ - int l, r, p, key; - - // Get the array - // Sort the array if not sorted - int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; - - // Starting index - l = 0; - - // length of array - r = 9; - - // Checking for 5 - - // Key to be searched in the array - key = 5; - - // Search the key using ternarySearch - p = ternarySearch(l, r, key, ar); - - // Print the result - printf("Index of %d is %d\n", key, p); - - // Checking for 50 - - // Key to be searched in the array - key = 50; - - // Search the key using ternarySearch - p = ternarySearch(l, r, key, ar); - - // Print the result - printf("Index of %d is %d", key, p); -} \ No newline at end of file + +#include + +// Function to perform Ternary Search +int ternarySearch(int l, int r, int key, int ar[]) +{ + if (r >= l) + { + + // Find the mid1 and mid2 + int mid1 = l + (r - l) / 3; + int mid2 = r - (r - l) / 3; + + // Check if key is present at any mid + if (ar[mid1] == key) + { + return mid1; + } + if (ar[mid2] == key) + { + return mid2; + } + + // Since key is not present at mid, + // check in which region it is present + // then repeat the Search operation + // in that region + + if (key < ar[mid1]) + { + + // The key lies in between l and mid1 + return ternarySearch(l, mid1 - 1, key, ar); + } + else if (key > ar[mid2]) + { + + // The key lies in between mid2 and r + return ternarySearch(mid2 + 1, r, key, ar); + } + else + { + + // The key lies in between mid1 and mid2 + return ternarySearch(mid1 + 1, mid2 - 1, key, ar); + } + } + + // Key not found + return -1; +} + +// Driver code +int main() +{ + int l, r, p, key; + + // Get the array + // Sort the array if not sorted + int ar[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + + // Starting index + l = 0; + + // length of array + r = 9; + + // Checking for 5 + + // Key to be searched in the array + key = 5; + + // Search the key using ternarySearch + p = ternarySearch(l, r, key, ar); + + // Print the result + printf("Index of %d is %d\n", key, p); + + // Checking for 50 + + // Key to be searched in the array + key = 50; + + // Search the key using ternarySearch + p = ternarySearch(l, r, key, ar); + + // Print the result + printf("Index of %d is %d", key, p); +} \ No newline at end of file diff --git a/sorting/Bead_Sort.c b/sorting/Bead_Sort.c index 1c244f87..a9d9510c 100644 --- a/sorting/Bead_Sort.c +++ b/sorting/Bead_Sort.c @@ -1,4 +1,4 @@ -//sorting of array list using bead sort +// sorting of array list using bead sort #include #include @@ -6,13 +6,13 @@ void display(int *arr, int n) { - int i; - for (i = 0; i < n; i++) - { - printf("%d ", arr[i]); - } + int i; + for (i = 0; i < n; i++) + { + printf("%d ", arr[i]); + } - printf("\n"); + printf("\n"); } /*This is where the sorting of the array takes place @@ -21,65 +21,65 @@ void display(int *arr, int n) */ void bead_sort(int *a, int len) { - int i, j, max, sum; - unsigned char *beads; + int i, j, max, sum; + unsigned char *beads; #define BEAD(i, j) beads[i * max + j] - for (i = 1, max = a[0]; i < len; i++) - if (a[i] > max) - max = a[i]; + for (i = 1, max = a[0]; i < len; i++) + if (a[i] > max) + max = a[i]; - beads = calloc(1, max * len); + beads = calloc(1, max * len); - /* mark the beads */ - for (i = 0; i < len; i++) - for (j = 0; j < a[i]; j++) - BEAD(i, j) = 1; + /* mark the beads */ + for (i = 0; i < len; i++) + for (j = 0; j < a[i]; j++) + BEAD(i, j) = 1; - for (j = 0; j < max; j++) - { - /* count how many beads are on each post */ - for (sum = i = 0; i < len; i++) - { - sum += BEAD(i, j); - BEAD(i, j) = 0; - } - /* mark bottom sum beads */ - for (i = len - sum; i < len; i++) - BEAD(i, j) = 1; - } + for (j = 0; j < max; j++) + { + /* count how many beads are on each post */ + for (sum = i = 0; i < len; i++) + { + sum += BEAD(i, j); + BEAD(i, j) = 0; + } + /* mark bottom sum beads */ + for (i = len - sum; i < len; i++) + BEAD(i, j) = 1; + } - for (i = 0; i < len; i++) - { - for (j = 0; j < max && BEAD(i, j); j++) - ; - a[i] = j; - } - free(beads); + for (i = 0; i < len; i++) + { + for (j = 0; j < max && BEAD(i, j); j++) + ; + a[i] = j; + } + free(beads); } int main(int argc, const char *argv[]) { - int n; - printf("Enter size of array:\n"); - scanf("%d", &n); // E.g. 8 1 2 3 + int n; + printf("Enter size of array:\n"); + scanf("%d", &n); // E.g. 8 1 2 3 - printf("Enter the elements of the array\n"); - int i; - int *arr = (int *)malloc(n * sizeof(int)); - for (i = 0; i < n; i++) - { - scanf("%d", &arr[i]); - } + printf("Enter the elements of the array\n"); + int i; + int *arr = (int *)malloc(n * sizeof(int)); + for (i = 0; i < n; i++) + { + scanf("%d", &arr[i]); + } - printf("Original array: "); - display(arr, n); + printf("Original array: "); + display(arr, n); - bead_sort(arr, n); + bead_sort(arr, n); - printf("Sorted array: "); - display(arr, n); + printf("Sorted array: "); + display(arr, n); - free(arr); - return 0; + free(arr); + return 0; } diff --git a/sorting/Bogo_Sort.c b/sorting/Bogo_Sort.c index 8ad36b40..26f8fa35 100644 --- a/sorting/Bogo_Sort.c +++ b/sorting/Bogo_Sort.c @@ -1,40 +1,46 @@ +#include #include #include -#include bool check_sorted(int *a, int n) { - while ( --n >= 1 ) { - if ( a[n] < a[n-1] ) return false; - } - return true; + while (--n >= 1) + { + if (a[n] < a[n - 1]) + return false; + } + return true; } void shuffle(int *a, int n) { - int i, t, r; - for(i=0; i < n; i++) { - t = a[i]; - r = rand() % n; - a[i] = a[r]; - a[r] = t; - } + int i, t, r; + for (i = 0; i < n; i++) + { + t = a[i]; + r = rand() % n; + a[i] = a[r]; + a[r] = t; + } } void sort(int *a, int n) { - while ( !check_sorted(a, n) ) shuffle(a, n); + while (!check_sorted(a, n)) + shuffle(a, n); } int main() { - int numbers[6]; - int i; - printf("Enter 6 numbers unsorted \n\n"); - for(i=0;i<6;i++){ - scanf("%d",&numbers[i]); - } - sort(numbers, 6); - for (i=0; i < 6; i++) printf("%d ", numbers[i]); - printf("\n"); + int numbers[6]; + int i; + printf("Enter 6 numbers unsorted \n\n"); + for (i = 0; i < 6; i++) + { + scanf("%d", &numbers[i]); + } + sort(numbers, 6); + for (i = 0; i < 6; i++) + printf("%d ", numbers[i]); + printf("\n"); } diff --git a/sorting/Bubble_Sort.c b/sorting/Bubble_Sort.c index 7d51bc13..2a042985 100644 --- a/sorting/Bubble_Sort.c +++ b/sorting/Bubble_Sort.c @@ -1,4 +1,4 @@ -//sorting of array list using bubble sort +// sorting of array list using bubble sort #include #include diff --git a/sorting/Bucket_Sort.c b/sorting/Bucket_Sort.c index 12b5eb7e..9d65430c 100644 --- a/sorting/Bucket_Sort.c +++ b/sorting/Bucket_Sort.c @@ -1,13 +1,13 @@ /* -* Algorithm : Bucket Sort -* Time-Complexity : O(n) -*/ + * Algorithm : Bucket Sort + * Time-Complexity : O(n) + */ +#include #include #include -#include -#define NARRAY 8 /* array size */ -#define NBUCKET 5 /* bucket size */ +#define NARRAY 8 /* array size */ +#define NBUCKET 5 /* bucket size */ #define INTERVAL 10 /* bucket range */ struct Node @@ -24,32 +24,32 @@ int getBucketIndex(int value); void BucketSort(int arr[]) { - int i,j; + int i, j; struct Node **buckets; /* allocate memory for array of pointers to the buckets */ - buckets = (struct Node **)malloc(sizeof(struct Node*) * NBUCKET); + buckets = (struct Node **)malloc(sizeof(struct Node *) * NBUCKET); /* initialize pointers to the buckets */ - for(i = 0; i < NBUCKET; ++i) + for (i = 0; i < NBUCKET; ++i) { buckets[i] = NULL; } /* put items into the buckets */ /* creates a link list in each bucket slot */ - for(i = 0; i < NARRAY; ++i) + for (i = 0; i < NARRAY; ++i) { struct Node *current; int pos = getBucketIndex(arr[i]); - current = (struct Node *) malloc(sizeof(struct Node)); + current = (struct Node *)malloc(sizeof(struct Node)); current->data = arr[i]; current->next = buckets[pos]; buckets[pos] = current; } /* check what's in each bucket */ - for(i = 0; i < NBUCKET; i++) + for (i = 0; i < NBUCKET; i++) { printf("Bucket[\"%d\"] : ", i); printBuckets(buckets[i]); @@ -57,7 +57,7 @@ void BucketSort(int arr[]) } /* sorting bucket using Insertion Sort */ - for(i = 0; i < NBUCKET; ++i) + for (i = 0; i < NBUCKET; ++i) { buckets[i] = InsertionSort(buckets[i]); } @@ -65,7 +65,7 @@ void BucketSort(int arr[]) /* check what's in each bucket */ printf("--------------\n"); printf("Buckets after sorted\n"); - for(i = 0; i < NBUCKET; i++) + for (i = 0; i < NBUCKET; i++) { printf("Bucket[\"%d\"] : ", i); printBuckets(buckets[i]); @@ -73,11 +73,11 @@ void BucketSort(int arr[]) } /* put items back to original array */ - for(j =0, i = 0; i < NBUCKET; ++i) + for (j = 0, i = 0; i < NBUCKET; ++i) { struct Node *node; node = buckets[i]; - while(node) + while (node) { // precondition for avoiding out of bounds by the array @@ -88,11 +88,11 @@ void BucketSort(int arr[]) } /* free memory */ - for(i = 0; i < NBUCKET; ++i) + for (i = 0; i < NBUCKET; ++i) { struct Node *node; node = buckets[i]; - while(node) + while (node) { struct Node *tmp; tmp = node; @@ -107,9 +107,9 @@ void BucketSort(int arr[]) /* Insertion Sort */ struct Node *InsertionSort(struct Node *list) { - struct Node *k,*nodeList; + struct Node *k, *nodeList; /* need at least two items to sort */ - if(list == NULL || list->next == NULL) + if (list == NULL || list->next == NULL) { return list; } @@ -117,11 +117,11 @@ struct Node *InsertionSort(struct Node *list) nodeList = list; k = list->next; nodeList->next = NULL; /* 1st node is new list */ - while(k != NULL) + while (k != NULL) { struct Node *ptr; /* check if insert before first */ - if(nodeList->data > k->data) + if (nodeList->data > k->data) { struct Node *tmp; tmp = k; @@ -133,13 +133,14 @@ struct Node *InsertionSort(struct Node *list) // from begin up to end // finds [i] > [i+1] - for(ptr = nodeList; ptr->next != NULL; ptr = ptr->next) + for (ptr = nodeList; ptr->next != NULL; ptr = ptr->next) { - if(ptr->next->data > k->data) break; + if (ptr->next->data > k->data) + break; } // if found (above) - if(ptr->next != NULL) + if (ptr->next != NULL) { struct Node *tmp; tmp = k; @@ -159,15 +160,12 @@ struct Node *InsertionSort(struct Node *list) return nodeList; } -int getBucketIndex(int value) -{ - return value/INTERVAL; -} +int getBucketIndex(int value) { return value / INTERVAL; } void print(int ar[]) { int i; - for(i = 0; i < NARRAY; ++i) + for (i = 0; i < NARRAY; ++i) { printf("%d ", ar[i]); } @@ -177,7 +175,7 @@ void print(int ar[]) void printBuckets(struct Node *list) { struct Node *cur = list; - while(cur) + while (cur) { printf("%d ", cur->data); cur = cur->next; @@ -186,7 +184,7 @@ void printBuckets(struct Node *list) int main(void) { - int array[NARRAY] = {29,25,-1,49,9,37,21,43}; + int array[NARRAY] = {29, 25, -1, 49, 9, 37, 21, 43}; printf("Initial array\n"); print(array); diff --git a/sorting/Cocktail_Sort.c b/sorting/Cocktail_Sort.c index 909d54bf..504621b8 100644 --- a/sorting/Cocktail_Sort.c +++ b/sorting/Cocktail_Sort.c @@ -6,70 +6,70 @@ void cocktailSort(int arr[], int size) { - int i, changed = TRUE, temp, start = 0, end = size - 1; + int i, changed = TRUE, temp, start = 0, end = size - 1; - while (changed) - { - changed = FALSE; - for (i=start; i arr[i+1]) - { - temp = arr[i]; - arr[i] = arr[i+1]; - arr[i+1] = temp; - changed = TRUE; - } - } - end--; + changed = FALSE; + for (i = start; i < end; i++) + { + if (arr[i] > arr[i + 1]) + { + temp = arr[i]; + arr[i] = arr[i + 1]; + arr[i + 1] = temp; + changed = TRUE; + } + } + end--; - if (changed == FALSE) - { - break; - } - changed = FALSE; + if (changed == FALSE) + { + break; + } + changed = FALSE; - for (i=end-1; i>=start; i--) - { - if (arr[i+1] < arr[i]) - { - temp = arr[i+1]; - arr[i+1] = arr[i]; - arr[i] = temp; - changed = TRUE; - } + for (i = end - 1; i >= start; i--) + { + if (arr[i + 1] < arr[i]) + { + temp = arr[i + 1]; + arr[i + 1] = arr[i]; + arr[i] = temp; + changed = TRUE; + } + } + start++; } - start++; - } } int main() { - int i, n; + int i, n; - printf("Enter the size of the array: "); - scanf("%d", &n); - int* arr = (int*)malloc(sizeof(int) * n); + printf("Enter the size of the array: "); + scanf("%d", &n); + int *arr = (int *)malloc(sizeof(int) * n); - for (i = 0; i < n; i++) - { - printf("Number #%d: ", i + 1); - scanf("%d", &arr[i]); - } + for (i = 0; i < n; i++) + { + printf("Number #%d: ", i + 1); + scanf("%d", &arr[i]); + } - printf("You entered: "); - for (i=0; i -void max_heapify(int* a, int i, int n); -void heapsort(int* a, int n); -void build_maxheap(int* a, int n); +void max_heapify(int *a, int i, int n); +void heapsort(int *a, int n); +void build_maxheap(int *a, int n); -void max_heapify(int* a, int i, int n) { - int j, temp; - temp = a[i]; - j = 2 * i; - while (j <= n) { - if (j < n && a[j + 1] > a[j]) - j = j + 1; - if (temp > a[j]) { - break; - } else if (temp <= a[j]) { - a[j / 2] = a[j]; - j = 2 * j; - } - } - a[j / 2] = temp; - return; -} - -void heapsort(int* a, int n) { - int i, temp; - for (i = n; i >= 2; i--) { +void max_heapify(int *a, int i, int n) +{ + int j, temp; temp = a[i]; - a[i] = a[1]; - a[1] = temp; - max_heapify(a, 1, i - 1); - } + j = 2 * i; + while (j <= n) + { + if (j < n && a[j + 1] > a[j]) + j = j + 1; + if (temp > a[j]) + { + break; + } + else if (temp <= a[j]) + { + a[j / 2] = a[j]; + j = 2 * j; + } + } + a[j / 2] = temp; + return; } -void build_maxheap(int* a, int n) { - int i; - for (i = n / 2; i >= 1; i--) { - max_heapify(a, i, n); - } +void heapsort(int *a, int n) +{ + int i, temp; + for (i = n; i >= 2; i--) + { + temp = a[i]; + a[i] = a[1]; + a[1] = temp; + max_heapify(a, 1, i - 1); + } } -int main() { - int n, i; - printf("Enter number of elements of array\n"); - scanf("%d", &n); - int a[20]; - for (i = 1; i <= n; i++) { - printf("Enter Element %d\n", i); - scanf("%d", a + i); - } - - build_maxheap(a, n); - heapsort(a, n); - printf("Sorted Output\n"); - for (i = 1; i <= n; i++) { - printf("%d\n", a[i]); - } - - getchar(); +void build_maxheap(int *a, int n) +{ + int i; + for (i = n / 2; i >= 1; i--) + { + max_heapify(a, i, n); + } +} + +int main() +{ + int n, i; + printf("Enter number of elements of array\n"); + scanf("%d", &n); + int a[20]; + for (i = 1; i <= n; i++) + { + printf("Enter Element %d\n", i); + scanf("%d", a + i); + } + + build_maxheap(a, n); + heapsort(a, n); + printf("Sorted Output\n"); + for (i = 1; i <= n; i++) + { + printf("%d\n", a[i]); + } + + getchar(); } diff --git a/sorting/Pancake_Sort.c b/sorting/Pancake_Sort.c index 96271704..904b253e 100644 --- a/sorting/Pancake_Sort.c +++ b/sorting/Pancake_Sort.c @@ -1,6 +1,6 @@ // Sorting of array list using pancake sort -#include #include +#include /* Reverses the array */ void flip(int arr[], int i) @@ -38,7 +38,8 @@ void pancakeSort(int *arr, int n) // Find index of the maximum element in arr[0..curr_size-1] int maxElementIdx = findMax(arr, curr_size); - // Move the maximum element to end of current array if it's not already at the end + // Move the maximum element to end of current array if it's not already + // at the end if (maxElementIdx != curr_size - 1) { // To move at the end, first move maximum number to beginning diff --git a/sorting/Pigeonhole_Sort.c b/sorting/Pigeonhole_Sort.c index bbcfa0cb..8d882a26 100644 --- a/sorting/Pigeonhole_Sort.c +++ b/sorting/Pigeonhole_Sort.c @@ -3,71 +3,71 @@ void pigeonholeSort(int arr[], int size) { - int i, j, min = arr[0], max = arr[0], range; + int i, j, min = arr[0], max = arr[0], range; - // Getting range of the array using max and min - for (i=1; i max) - max = arr[i]; - } - range = max - min + 1; - - // Make 'holes' and put array's numbers in holes - int * holes = (int*)malloc(sizeof(int) * range); - for (i=0; i 0) + // Getting range of the array using max and min + for (i = 1; i < size; i++) { - arr[j] = i + min; - holes[i]--; - j++; + if (arr[i] < min) + min = arr[i]; + if (arr[i] > max) + max = arr[i]; } - } + range = max - min + 1; - free(holes); + // Make 'holes' and put array's numbers in holes + int *holes = (int *)malloc(sizeof(int) * range); + for (i = 0; i < range; i++) + { + holes[i] = 0; + } + for (i = 0; i < size; i++) + { + holes[arr[i] - min]++; + } + + // Copy the numbers back to the original array + j = 0; + for (i = 0; i < range; i++) + { + while (holes[i] > 0) + { + arr[j] = i + min; + holes[i]--; + j++; + } + } + + free(holes); } int main() { - int i, n; + int i, n; - printf("Enter the size of the array: "); - scanf("%d", &n); - int * arr = (int*)malloc(sizeof(int) * n); + printf("Enter the size of the array: "); + scanf("%d", &n); + int *arr = (int *)malloc(sizeof(int) * n); - for (i = 0; i < n; i++) - { - printf("Number #%d: ", i + 1); - scanf("%d", &arr[i]); - } + for (i = 0; i < n; i++) + { + printf("Number #%d: ", i + 1); + scanf("%d", &arr[i]); + } - printf("You entered: "); - for (i=0; i lower) { - // partitioning index is returned by the partition method , partition element is at its correct poition + // partitioning index is returned by the partition method , partition + // element is at its correct poition int partitionIndex = partition(arr, lower, upper); diff --git a/sorting/Selection_Sort.c b/sorting/Selection_Sort.c index a4a7c5de..52dcfb39 100644 --- a/sorting/Selection_Sort.c +++ b/sorting/Selection_Sort.c @@ -1,4 +1,4 @@ -//sorting of array list using selection sort +// sorting of array list using selection sort #include #include diff --git a/sorting/comb_sort.c b/sorting/comb_sort.c index a1ac017d..85d9a5b1 100644 --- a/sorting/comb_sort.c +++ b/sorting/comb_sort.c @@ -1,25 +1,25 @@ #include #include -#define SHRINK 1.3 //suggested shrink factor value +#define SHRINK 1.3 // suggested shrink factor value -void sort (int *numbers, int size) +void sort(int *numbers, int size) { - int gap = size; - while (gap > 1) //gap = 1 means that the array is sorted - { - gap = gap/SHRINK; - int i = 0; - while ((i + gap) < size) - { //similiar to the Shell Sort - if (numbers[i] > numbers[i + gap]) - { - int tmp = numbers[i]; - numbers[i] = numbers[i + gap]; - numbers[i + gap] = tmp; - } - i++; - } - } + int gap = size; + while (gap > 1) // gap = 1 means that the array is sorted + { + gap = gap / SHRINK; + int i = 0; + while ((i + gap) < size) + { // similiar to the Shell Sort + if (numbers[i] > numbers[i + gap]) + { + int tmp = numbers[i]; + numbers[i] = numbers[i + gap]; + numbers[i + gap] = tmp; + } + i++; + } + } } void display(int *array, int n) @@ -32,17 +32,17 @@ void display(int *array, int n) int main() { - int size = 6; - int *numbers = malloc(size*sizeof(int)); - printf("Insert %d unsorted numbers: \n", size); - int i; - for (i = 0; i < size; ++i) - scanf("%d", &numbers[i]); - printf("Initial array: "); - display(numbers, size); + int size = 6; + int *numbers = malloc(size * sizeof(int)); + printf("Insert %d unsorted numbers: \n", size); + int i; + for (i = 0; i < size; ++i) + scanf("%d", &numbers[i]); + printf("Initial array: "); + display(numbers, size); sort(numbers, size); - printf("Sorted array: "); + printf("Sorted array: "); display(numbers, size); free(numbers); - return 0; + return 0; } diff --git a/sorting/counting_Sort.c b/sorting/counting_Sort.c index efb159f2..a2927ef5 100644 --- a/sorting/counting_Sort.c +++ b/sorting/counting_Sort.c @@ -6,8 +6,8 @@ */ #include -#include #include +#include int main() { @@ -29,13 +29,13 @@ int main() memset(b, 0, (l + 1) * sizeof(b[0])); for (i = 0; i < n; i++) - b[a[i]]++; //hashing number to array index + b[a[i]]++; // hashing number to array index - for (i = 0; i < (l + 1); i++) //unstable , stabilized by prefix sum array + for (i = 0; i < (l + 1); i++) // unstable , stabilized by prefix sum array { if (b[i] > 0) { - while (b[i] != 0) //for case when number exists more than once + while (b[i] != 0) // for case when number exists more than once { printf("%d ", i); b[i]--; diff --git a/sorting/gnome_sort.c b/sorting/gnome_sort.c index 4c0ae61a..0e92f60e 100644 --- a/sorting/gnome_sort.c +++ b/sorting/gnome_sort.c @@ -6,18 +6,16 @@ void sort(int *numbers, int size) int pos = 0; while (pos < size) { - if (pos == 0) - pos = 1; - if (numbers[pos] >= numbers[pos-1] || pos == 0) + if (pos == 0) + pos = 1; + if (numbers[pos] >= numbers[pos - 1] || pos == 0) pos++; else { - int tmp = numbers[pos-1]; - numbers[pos-1] = numbers[pos]; + int tmp = numbers[pos - 1]; + numbers[pos - 1] = numbers[pos]; numbers[pos] = tmp; pos--; - - } } } @@ -34,7 +32,7 @@ int main() { int size = 6; int i; - int *numbers = malloc(size*sizeof(int)); + int *numbers = malloc(size * sizeof(int)); printf("Insert %d unsorted numbers: \n", size); for (i = 0; i < size; ++i) scanf("%d", &numbers[i]); diff --git a/sorting/insertion_Sort.c b/sorting/insertion_Sort.c index 05eef233..f9f87b8e 100644 --- a/sorting/insertion_Sort.c +++ b/sorting/insertion_Sort.c @@ -1,4 +1,4 @@ -//sorting of array list using insertion sort +// sorting of array list using insertion sort #include #include diff --git a/sorting/merge_sort.c b/sorting/merge_sort.c index ea2bfba3..bbc00144 100644 --- a/sorting/merge_sort.c +++ b/sorting/merge_sort.c @@ -1,7 +1,7 @@ #include #include -void swap(int *a, int *b) //To swap the variables// +void swap(int *a, int *b) // To swap the variables// { int t; t = *a; @@ -9,7 +9,7 @@ void swap(int *a, int *b) //To swap the variables// *b = t; } -void merge(int a[], int l, int r, int n) //To merge // +void merge(int a[], int l, int r, int n) // To merge // { int *b = (int *)malloc(n * sizeof(int)); int c = l; @@ -69,7 +69,7 @@ void merge_sort(int *a, int n, int l, int r) } } int main(void) -{ //main function// +{ // main function// int *a, n, i; scanf("%d", &n); a = (int *)malloc(n * sizeof(int)); diff --git a/sorting/merge_sort_nr.c b/sorting/merge_sort_nr.c index 624b7411..219822c4 100644 --- a/sorting/merge_sort_nr.c +++ b/sorting/merge_sort_nr.c @@ -1,93 +1,92 @@ /* Program to demonstrate non recursive merge sort */ -/* Merge sort is an effective sorting algorithm which falls under divide and conquer paradigm and produces a stable sort. - Merge sort repeatedly breaks down a list into several sublists until each sublist consists of a single element and merging those - sublists in a manner that results into a sorted list. +/* Merge sort is an effective sorting algorithm which falls under divide and +conquer paradigm and produces a stable sort. Merge sort repeatedly breaks down a +list into several sublists until each sublist consists of a single element and +merging those sublists in a manner that results into a sorted list. Bottom-Up Merge Sort Implementation: -The Bottom-Up merge sort approach uses iterative methodology. It starts with the “single-element” array, and combines two adjacent elements and -also sorting the two at the same time. -The combined-sorted arrays are again combined and sorted with each other until one single unit of sorted array is achieved. */ +The Bottom-Up merge sort approach uses iterative methodology. It starts with the +“single-element” array, and combines two adjacent elements and also sorting the +two at the same time. The combined-sorted arrays are again combined and sorted +with each other until one single unit of sorted array is achieved. */ -#include +#include -void mergesort(int x[ ] , int n) ; -void show(int x[ ] , int n) ; +void mergesort(int x[], int n); +void show(int x[], int n); - - -void mergesort(int x[ ] , int n) +void mergesort(int x[], int n) { - int temp[50] , i , j , k , lb1 , lb2 , ub1 , ub2 , size ; + int temp[50], i, j, k, lb1, lb2, ub1, ub2, size; - size=1 ; - while(size pmcost Interactive partial match expers on */ +#include #include #include -#include #include // MULTIKEY QUICKSORT @@ -18,11 +18,11 @@ #define min(a, b) ((a) <= (b) ? (a) : (b)) #endif -#define swap(a, b) \ - { \ - char *t = x[a]; \ - x[a] = x[b]; \ - x[b] = t; \ +#define swap(a, b) \ + { \ + char *t = x[a]; \ + x[a] = x[b]; \ + x[b] = t; \ } #define i2c(i) x[i][depth] @@ -84,10 +84,7 @@ void ssort1(char *x[], int n, int depth) ssort1(x + n - r, r, depth); } -void ssort1main(char *x[], int n) -{ - ssort1(x, n, 0); -} +void ssort1main(char *x[], int n) { ssort1(x, n, 0); } // ssort2 -- Faster Version of Multikey Quicksort @@ -101,11 +98,11 @@ void vecswap2(char **a, char **b, int n) } } -#define swap2(a, b) \ - { \ - t = *(a); \ - *(a) = *(b); \ - *(b) = t; \ +#define swap2(a, b) \ + { \ + t = *(a); \ + *(a) = *(b); \ + *(b) = t; \ } #define ptr2char(i) (*(*(i) + depth)) @@ -277,8 +274,7 @@ void insert2(char *s) // *p = (Tptr) malloc(sizeof(Tnode)); if (bufn-- == 0) { - buf = (Tptr)malloc(BUFSIZE * - sizeof(Tnode)); + buf = (Tptr)malloc(BUFSIZE * sizeof(Tnode)); freearr[freen++] = (void *)buf; bufn = BUFSIZE - 1; } @@ -364,8 +360,7 @@ void pmsearch(Tptr p, char *s) if (p->splitchar && *s) pmsearch(p->eqkid, s + 1); if (*s == 0 && p->splitchar == 0) - srcharr[srchtop++] = - (char *)p->eqkid; + srcharr[srchtop++] = (char *)p->eqkid; if (*s == '.' || *s > p->splitchar) pmsearch(p->hikid, s); } @@ -380,12 +375,10 @@ void nearsearch(Tptr p, char *s, int d) if (p->splitchar == 0) { if ((int)strlen(s) <= d) - srcharr[srchtop++] = - (char *)p->eqkid; + srcharr[srchtop++] = (char *)p->eqkid; } else - nearsearch(p->eqkid, *s ? s + 1 : s, - (*s == p->splitchar) ? d : d - 1); + nearsearch(p->eqkid, *s ? s + 1 : s, (*s == p->splitchar) ? d : d - 1); if (d > 0 || *s > p->splitchar) nearsearch(p->hikid, s, d); } diff --git a/sorting/partition_Sort.c b/sorting/partition_Sort.c index a0b9f575..b6da9be2 100644 --- a/sorting/partition_Sort.c +++ b/sorting/partition_Sort.c @@ -1,5 +1,5 @@ -#include #include +#include void swap(int *a, int *b) { diff --git a/sorting/radix_sort.c b/sorting/radix_sort.c index 9ceca1a9..97bf43c9 100644 --- a/sorting/radix_sort.c +++ b/sorting/radix_sort.c @@ -1,74 +1,73 @@ -#include - +#include + int largest(int a[], int n) { int large = a[0], i; - for(i = 1; i < n; i++) + for (i = 1; i < n; i++) { - if(large < a[i]) + if (large < a[i]) large = a[i]; } return large; } - void RadixSort(int a[], int n) { int bucket[10][10], bucket_count[10]; - int i, j, k, remainder, NOP=0, divisor=1, large, pass; - + int i, j, k, remainder, NOP = 0, divisor = 1, large, pass; + large = largest(a, n); - printf("The large element %d\n",large); - while(large > 0) + printf("The large element %d\n", large); + while (large > 0) { NOP++; - large/=10; + large /= 10; } - - for(pass = 0; pass < NOP; pass++) + + for (pass = 0; pass < NOP; pass++) { - for(i = 0; i < 10; i++) + for (i = 0; i < 10; i++) { bucket_count[i] = 0; } - for(i = 0; i < n; i++) + for (i = 0; i < n; i++) { remainder = (a[i] / divisor) % 10; bucket[remainder][bucket_count[remainder]] = a[i]; bucket_count[remainder] += 1; } - + i = 0; - for(k = 0; k < 10; k++) + for (k = 0; k < 10; k++) { - for(j = 0; j < bucket_count[k]; j++) + for (j = 0; j < bucket_count[k]; j++) { a[i] = bucket[k][j]; i++; } } divisor *= 10; - - for(i = 0; i < n; i++) - printf("%d ",a[i]); + + for (i = 0; i < n; i++) + printf("%d ", a[i]); printf("\n"); } } - + int main() { int i, n, a[10]; printf("Enter the number of elements :: "); - scanf("%d",&n); + scanf("%d", &n); printf("Enter the elements :: "); - for(i = 0; i < n; i++) + for (i = 0; i < n; i++) { - scanf("%d",&a[i]); + scanf("%d", &a[i]); } - RadixSort(a,n); + RadixSort(a, n); printf("The sorted elements are :: "); - for(i = 0; i < n; i++) - printf("%d ",a[i]); + for (i = 0; i < n; i++) + printf("%d ", a[i]); printf("\n"); return 0; } diff --git a/sorting/radix_sort_2.c b/sorting/radix_sort_2.c index 1c4e2ad7..d1902e2d 100644 --- a/sorting/radix_sort_2.c +++ b/sorting/radix_sort_2.c @@ -1,4 +1,4 @@ -//sorting of array list using Radix sort +// sorting of array list using Radix sort #include #include @@ -7,40 +7,42 @@ // Utility function to get the maximum value in ar[] int MAX(int *ar, int size) { - int i, max = ar[0]; - for (i = 0; i < size; i++) - { - if (ar[i] > max) - max = ar[i]; - } - return max; + int i, max = ar[0]; + for (i = 0; i < size; i++) + { + if (ar[i] > max) + max = ar[i]; + } + return max; } // Counting sort according to the digit represented by place void countSort(int *arr, int n, int place) { - int i, freq[range] = {0}; - int *output = (int *)malloc(n * sizeof(int)); + int i, freq[range] = {0}; + int *output = (int *)malloc(n * sizeof(int)); - // Store count of occurences in freq[] - for (i = 0; i < n; i++) - freq[(arr[i] / place) % range]++; + // Store count of occurences in freq[] + for (i = 0; i < n; i++) + freq[(arr[i] / place) % range]++; - // Change freq[i] so that it contains the actual position of the digit in output[] - for (i = 1; i < range; i++) - freq[i] += freq[i - 1]; + // Change freq[i] so that it contains the actual position of the digit in + // output[] + for (i = 1; i < range; i++) + freq[i] += freq[i - 1]; - // Build the output array - for (i = n - 1; i >= 0; i--) - { - output[freq[(arr[i] / place) % range] - 1] = arr[i]; - freq[(arr[i] / place) % range]--; - } + // Build the output array + for (i = n - 1; i >= 0; i--) + { + output[freq[(arr[i] / place) % range] - 1] = arr[i]; + freq[(arr[i] / place) % range]--; + } - // Copy the output array to arr[], so it contains numbers according to the current digit - for (i = 0; i < n; i++) - arr[i] = output[i]; - free(output); + // Copy the output array to arr[], so it contains numbers according to the + // current digit + for (i = 0; i < n; i++) + arr[i] = output[i]; + free(output); } /*This is where the sorting of the array takes place @@ -48,49 +50,50 @@ void countSort(int *arr, int n, int place) n --- Array Size max --- Maximum element in Array */ -void radixsort2(int *arr, int n, int max) //max is the maximum element in the array +void radixsort2(int *arr, int n, + int max) // max is the maximum element in the array { - int mul = 1; - while (max) - { - countSort(arr, n, mul); - mul *= 10; - max /= 10; - } + int mul = 1; + while (max) + { + countSort(arr, n, mul); + mul *= 10; + max /= 10; + } } void display(int *arr, int N) { - for (int i = 0; i < N; i++) - printf("%d, ", arr[i]); - putchar('\n'); + for (int i = 0; i < N; i++) + printf("%d, ", arr[i]); + putchar('\n'); } int main(int argc, const char *argv[]) { - int n; - printf("Enter size of array:\n"); - scanf("%d", &n); // E.g. 8 + int n; + printf("Enter size of array:\n"); + scanf("%d", &n); // E.g. 8 - printf("Enter the elements of the array\n"); - int i; - int *arr = (int *)malloc(n * sizeof(int)); - for (i = 0; i < n; i++) - { - scanf("%d", &arr[i]); - } + printf("Enter the elements of the array\n"); + int i; + int *arr = (int *)malloc(n * sizeof(int)); + for (i = 0; i < n; i++) + { + scanf("%d", &arr[i]); + } - printf("Original array: "); - display(arr, n); // Original array : 10 11 9 8 4 7 3 8 + printf("Original array: "); + display(arr, n); // Original array : 10 11 9 8 4 7 3 8 - int max; - max = MAX(arr, n); + int max; + max = MAX(arr, n); - radixsort2(arr, n, max); + radixsort2(arr, n, max); - printf("Sorted array: "); - display(arr, n); // Sorted array : 3 4 7 8 8 9 10 11 + printf("Sorted array: "); + display(arr, n); // Sorted array : 3 4 7 8 8 9 10 11 - free(arr); - return 0; + free(arr); + return 0; } diff --git a/sorting/random_quick_sort.c b/sorting/random_quick_sort.c index 9d07736c..71cac361 100644 --- a/sorting/random_quick_sort.c +++ b/sorting/random_quick_sort.c @@ -1,9 +1,10 @@ /* Randomised quick sort implementation in C language. -In normal quick sort, pivot chosen to partition is either the first or the last element of the array. -This can take time O(n*n) to sort in the worst case. -Now in randomised quick sort, pivot is randomly chosen and then recursively sort the left and right sub-arrays. -The expected running time of the algorithm is O(nlog(n)). +In normal quick sort, pivot chosen to partition is either the first or the last +element of the array. This can take time O(n*n) to sort in the worst case. Now +in randomised quick sort, pivot is randomly chosen and then recursively sort the +left and right sub-arrays. The expected running time of the algorithm is +O(nlog(n)). */ #include #include @@ -53,7 +54,8 @@ void random_quick(int *a, int left, int right) i = getBig(a, i, right, pivot); j = getSmall(a, j, left, pivot); } - // after separating the smaller and greater elements, there are 3 cases possible + // after separating the smaller and greater elements, there are 3 cases + // possible if (pivot_index > j && pivot_index > i) { // case 1. When the pivot element index is greater than both i and j