diff --git a/.gitignore b/.gitignore index b80ba84..18c1846 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,10 @@ Informe.pdf doc/*.aux +doc/*.out doc/*.log doc/*.synctex.gz doc/*.toc +test/test *.o sort +core diff --git a/Makefile b/Makefile index 31c3f17..def505a 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,7 @@ CC=gcc -CFLAGS=-Wall -Werror -CPPFLAGS+=-Isrc/include +CFLAGS=-Wall -Isrc/include -DDEBUG -g #LDFLAGS=-lm -SRC=src/sort.c src/random.c +SRC=src/sort.c src/random.c src/bubble_sort.c src/timer.c OBJ=$(SRC:.c=.o) all: sort informe @@ -17,7 +16,11 @@ ifneq (, $(shell which pdflatex)) mv doc/Informe.pdf Informe.pdf endif -clean: cleansort cleaninforme +test: + make -C test + test/test + +clean: cleansort cleaninforme cleantest cleansort: rm -f src/*.o sort @@ -26,4 +29,7 @@ cleaninforme: make -C doc clean rm -f Informe.pdf -.PHONY: all sort informe clean cleansort cleaninforme +cleantest: + make -C test clean + +.PHONY: all sort informe test clean cleansort cleaninforme cleantest diff --git a/doc/Informe.tex b/doc/Informe.tex index 6521b74..910bc03 100644 --- a/doc/Informe.tex +++ b/doc/Informe.tex @@ -12,6 +12,17 @@ \usepackage[left=2cm,right=2cm,top=2cm,bottom=2cm,a4paper]{geometry} \usepackage{amsmath} +\usepackage{listings} +\lstset{ + basicstyle=\small\ttfamily, + columns=flexible, + breaklines=true +} + +\usepackage{hyperref} +\hypersetup{pdftex,colorlinks=true,allcolors=black,bookmarks} +\usepackage{hypcap} + \pretitle{% \begin{center} \LARGE @@ -59,6 +70,7 @@ Xavier Canales \subsection{Quick Sort} \subsection{Bubble Sort} +\lstinputlisting{psuedo/bubblesort.txt} \subsection{Bitonic Sort} diff --git a/doc/Makefile b/doc/Makefile index 788bb80..a0a7aae 100644 --- a/doc/Makefile +++ b/doc/Makefile @@ -4,6 +4,6 @@ informe: pdflatex -synctex=1 -interaction=nonstopmode "Informe.tex" clean: - rm -f *.log *.toc *.gz *.aux Informe.pdf + rm -f *.log *.toc *.gz *.aux *.out Informe.pdf .PHONY: informe clean diff --git a/doc/psuedo/bubblesort.txt b/doc/psuedo/bubblesort.txt new file mode 100644 index 0000000..c3cc70c --- /dev/null +++ b/doc/psuedo/bubblesort.txt @@ -0,0 +1,9 @@ +cuentaDeElementos := n +repetir + haCambiado := falso + disminuir cuentaDeElementos + repetir con indice desde 1 a cuentaDeElementos + if (elemento en indice) > (elemento en (indice + 1)) + intercambiar (elemento en indice) con (elemento en (indice + 1)) + haCambiado := falso +hasta haCambiado = verdad diff --git a/src/bubble_sort.c b/src/bubble_sort.c new file mode 100644 index 0000000..5b10ec0 --- /dev/null +++ b/src/bubble_sort.c @@ -0,0 +1,33 @@ +/* + * Copyright 2018 Christopher Cromer + * Copyright 2018 Rodolfo Cuevas + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +void bubble_sort(int *array, int n) { + int i; + int j = n; + int temp; + int flag = 1; + while (flag) { + flag = 0; + for (i = 1; i < j; i++) { + if (array[i] < array[i - 1]) { + temp = array[i]; + array[i] = array[i - 1]; + array[i - 1] = temp; + flag = 1; + } + } + j--; + } +} diff --git a/src/include/bubble_sort.h b/src/include/bubble_sort.h new file mode 100644 index 0000000..fc31615 --- /dev/null +++ b/src/include/bubble_sort.h @@ -0,0 +1,19 @@ +/* + * Copyright 2018 Christopher Cromer + * Copyright 2018 Rodolfo Cuevas + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _SORT_BUBBLE + #define _SORT_BUBBLE + void bubble_sort(int *array, int n); +#endif diff --git a/src/include/timer.h b/src/include/timer.h new file mode 100644 index 0000000..c899263 --- /dev/null +++ b/src/include/timer.h @@ -0,0 +1,22 @@ +/* + * Copyright 2018 Christopher Cromer + * Copyright 2018 Rodolfo Cuevas + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _SORT_TIMER + #define _SORT_TIMER + void start_timer(); + void stop_timer(); + void print_timer(); + long int get_timer(); +#endif diff --git a/src/sort.c b/src/sort.c index d779225..b22c41b 100644 --- a/src/sort.c +++ b/src/sort.c @@ -17,9 +17,13 @@ #include #include #include "random.h" +#include "timer.h" +#include "bubble_sort.h" #define SORT_VERSION "1.0.0" +static int *array; + /** * Imprimir el uso del programa */ @@ -36,6 +40,7 @@ void print_usage() { fprintf(stdout, " -e, --elegir el usuario debe elegir los \"n\" valores de\n"); fprintf(stdout, " elementos a ordenar, sin esta opción los\n"); fprintf(stdout, " valores son elegido por el programa al azar\n"); + fprintf(stdout, " -i, --imprimir imprimir el array antes y despues de ordenar\n"); fprintf(stdout, " -v, --version mostrar la versión del programa\n"); } @@ -48,15 +53,36 @@ void extra_algorithm() { exit(2); } +/** + * Imprimir un array + * @param *array El array a imprimir + * @param n La cantidad de elementos que están en el array + */ +void print_array(int *array, int n) { + int i; + for (i = 0; i < n; i++) { + fprintf(stdout, "%d ", array[i]); + } + fprintf(stdout, "\n"); +} + +/** + * Liberar la memoria al salir + */ +void cleanup() { + free(array); +} + /** * La entrada del programa * @param argc La cantidad de argumentos pasado al programa * @return Retorna el codigo de error o 0 por exito */ int main (int argc, char **argv) { - int i; + long long i; int n = 10; int elegir = 0; + int imprimir = 0; int algoritmo = -1; int opt; int long_index = 0; @@ -69,6 +95,7 @@ int main (int argc, char **argv) { {"selection", no_argument, 0, 's'}, {"n", required_argument, 0, 'n'}, {"elegir", no_argument, 0, 'e'}, + {"imprimir", no_argument, 0, 'i'}, {"version", no_argument, 0, 'v'}, {0, 0, 0, 0} }; @@ -117,7 +144,7 @@ int main (int argc, char **argv) { algoritmo = 5; break; case 'n': - n = atoi(optarg); + n = atol(optarg); if (n <= 1) { fprintf(stderr, "Error: n tiene que ser mayor de 1!\n"); return 3; @@ -126,6 +153,9 @@ int main (int argc, char **argv) { case 'e': elegir = 1; break; + case 'i': + imprimir = 1; + break; case 'v': printf("sort versión: %s\n", SORT_VERSION); return 0; @@ -136,23 +166,21 @@ int main (int argc, char **argv) { } } - if (algoritmo == -1) { - fprintf(stderr, "Error: No se seleccionó un algoritmo!\n"); + if (algoritmo < 0 || algoritmo > 5) { + fprintf(stderr, "Error: No se seleccionó un algoritmo valido!\n"); print_usage(); return 4; } - int array[n]; + array = malloc(sizeof(int) * n); + atexit(cleanup); // Llenar el array con valores para ordenar después for (i = 0; i < n; i++) { - if (elegir == 0) { - array[i] = gen_rand(0, 100000); - } - else { + if (elegir) { opt = 0; while (opt <= 1) { - fprintf(stdout, "Elegir elemento %d: ", i + 1); + fprintf(stdout, "Elegir elemento %lli: ", i + 1); fscanf(stdin, "%d", &opt); if (opt <= 1) { fprintf(stdout, "Número invalido! Tiene que ser mayor de 1!\n"); @@ -160,6 +188,44 @@ int main (int argc, char **argv) { } array[i] = opt; } + else { + array[i] = gen_rand(-1000, 5000); + } } + + if (imprimir) { + fprintf(stdout, "\nAntes:\n"); + print_array(array, n); + } + + if (algoritmo == 0) { + // merge sort + } + else if (algoritmo == 1) { + // quick sort + } + else if (algoritmo == 2) { + fprintf(stdout, "Bubble sort corriendo...\n"); + fflush(stdout); + start_timer(); + bubble_sort(array, n); + stop_timer(); + } + else if (algoritmo == 3) { + // bitonic sort + } + else if (algoritmo == 4) { + // count sort + } + else if (algoritmo == 5) { + // selection sort + } + + if (imprimir) { + fprintf(stdout, "\nDespués:\n"); + print_array(array, n); + } + + print_timer(); return 0; } diff --git a/src/timer.c b/src/timer.c new file mode 100644 index 0000000..014633c --- /dev/null +++ b/src/timer.c @@ -0,0 +1,67 @@ +/* + * Copyright 2018 Christopher Cromer + * Copyright 2018 Rodolfo Cuevas + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include "timer.h" + +/** + * Cuando empezó el timer + */ +static time_t start_time = 0; +/** + * Cuando terminó el timer + */ +static time_t stop_time = 0; + +/** + * Empezar el timer + */ +void start_timer() { + if (start_time != 0) { + fprintf(stderr, "Error: El temporizador ya comenzó!\n"); + } + else { + time(&start_time); + stop_time = 0; + } +} + +/** + * Terminar el timer + */ +void stop_timer() { + if (start_time == 0) { + fprintf(stderr, "Error: El temporizador no ha comenzado todavía!\n"); + } + else { + time(&stop_time); + } +} + +/** + * Imprimir el tiempo de ejecución + */ +void print_timer() { + fprintf(stdout, "Tiempo de ejecución: %ld segundos\n", (long int) (stop_time - start_time)); +} + +/** + * Devolver el tiempo que demoró en ejecutarse + * @return El tiempo que demoró + */ +long int get_timer() { + return (long int) (stop_time - start_time); +} diff --git a/test/Makefile b/test/Makefile new file mode 100644 index 0000000..2b8cab0 --- /dev/null +++ b/test/Makefile @@ -0,0 +1,15 @@ +CC=gcc +CFLAGS=-Wall -I../src/include -DDEBUG -g +SRC=test.c +OBJ=$(SRC:.c=.o) +OBJ+=../src/random.o ../src/bubble_sort.o ../src/timer.o + +all: test + +test: $(OBJ) + $(CC) -o $@ $^ $(LDFLAGS) + +clean: + rm -f *.o test + +.PHONY: all test clean diff --git a/test/test.c b/test/test.c new file mode 100644 index 0000000..05e246f --- /dev/null +++ b/test/test.c @@ -0,0 +1,116 @@ +/* + * Copyright 2018 Christopher Cromer + * Copyright 2018 Rodolfo Cuevas + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include "random.h" +#include "bubble_sort.h" + +static int *test_case; +static int *test_array; +static int *qarray; + +/** + * Este función va a comparar valores para devolver los valores en orden ascendida + * @param a El primer valor a comparar + * @param b El segundo valor a comparar + * @return Retorna la comparación de los dos argumentos + */ +int compar(const void *a, const void *b) { + return (*(int*) a - *(int*) b); +} + +/** + * Limpiar la memoria al salir + */ +void cleanup() { + free(test_case); + free(test_array); + free(qarray); +} + +/** + * El programa de test + */ +int main(int argc, char **argv) { + int n = 50000; + int i; + int gen; + int pass = 1; + int passed = 0; + int failed = 0; + + test_case = malloc(sizeof(int) * n); + qarray = malloc(sizeof(int) * n); + test_array = malloc(sizeof(int) * n); + + atexit(cleanup); + + fprintf(stdout, "Running tests:\n"); + + // Test random number generation + fprintf(stdout, "\trandom generation: "); + fflush(stdout); + for (i = 0; i < 5000000; i++) { + gen = gen_rand(-1000, 1000); + if ((gen < -1000 || gen > 1000) && pass) { + fprintf(stdout, "fail\n"); + failed++; + pass = 0; + } + } + if (pass) { + fprintf(stdout, "pass\n"); + passed++; + } + pass = 1; + + // Prepare for sort tests + for (i = 0; i < n; i++) { + test_case[i] = gen_rand(-20, 100); + } + memcpy(qarray, test_case, sizeof(int) * n); + memcpy(test_array, test_case, sizeof(int) * n); + qsort(qarray, n, sizeof(int), compar); + + // Test bubble sort + fprintf(stdout, "\tbubble sort: "); + fflush(stdout); + bubble_sort(test_array, n); + for (i = 0; i < n; i++) { + if (test_array[i] != qarray[i] && pass) { + fprintf(stdout, "fail\n"); + failed++; + pass = 0; + } + } + if (pass) { + fprintf(stdout, "pass\n"); + passed++; + } + pass = 1; + + fprintf(stdout, "%d tests passed\n", passed); + fprintf(stdout, "%d tests failed\n", failed); + + if (failed == 0) { + return 0; + } + else { + return 1; + } +}