Merge branch 'bubblesort' of UBB/sort into master

This commit is contained in:
Chris Cromer 2018-11-11 19:17:20 -03:00 committed by Gitea
commit ea7d80cf09
12 changed files with 384 additions and 16 deletions

3
.gitignore vendored
View File

@ -1,7 +1,10 @@
Informe.pdf Informe.pdf
doc/*.aux doc/*.aux
doc/*.out
doc/*.log doc/*.log
doc/*.synctex.gz doc/*.synctex.gz
doc/*.toc doc/*.toc
test/test
*.o *.o
sort sort
core

View File

@ -1,8 +1,7 @@
CC=gcc CC=gcc
CFLAGS=-Wall -Werror CFLAGS=-Wall -Isrc/include -DDEBUG -g
CPPFLAGS+=-Isrc/include
#LDFLAGS=-lm #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) OBJ=$(SRC:.c=.o)
all: sort informe all: sort informe
@ -17,7 +16,11 @@ ifneq (, $(shell which pdflatex))
mv doc/Informe.pdf Informe.pdf mv doc/Informe.pdf Informe.pdf
endif endif
clean: cleansort cleaninforme test:
make -C test
test/test
clean: cleansort cleaninforme cleantest
cleansort: cleansort:
rm -f src/*.o sort rm -f src/*.o sort
@ -26,4 +29,7 @@ cleaninforme:
make -C doc clean make -C doc clean
rm -f Informe.pdf 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

View File

@ -12,6 +12,17 @@
\usepackage[left=2cm,right=2cm,top=2cm,bottom=2cm,a4paper]{geometry} \usepackage[left=2cm,right=2cm,top=2cm,bottom=2cm,a4paper]{geometry}
\usepackage{amsmath} \usepackage{amsmath}
\usepackage{listings}
\lstset{
basicstyle=\small\ttfamily,
columns=flexible,
breaklines=true
}
\usepackage{hyperref}
\hypersetup{pdftex,colorlinks=true,allcolors=black,bookmarks}
\usepackage{hypcap}
\pretitle{% \pretitle{%
\begin{center} \begin{center}
\LARGE \LARGE
@ -59,6 +70,7 @@ Xavier Canales
\subsection{Quick Sort} \subsection{Quick Sort}
\subsection{Bubble Sort} \subsection{Bubble Sort}
\lstinputlisting{psuedo/bubblesort.txt}
\subsection{Bitonic Sort} \subsection{Bitonic Sort}

View File

@ -4,6 +4,6 @@ informe:
pdflatex -synctex=1 -interaction=nonstopmode "Informe.tex" pdflatex -synctex=1 -interaction=nonstopmode "Informe.tex"
clean: clean:
rm -f *.log *.toc *.gz *.aux Informe.pdf rm -f *.log *.toc *.gz *.aux *.out Informe.pdf
.PHONY: informe clean .PHONY: informe clean

View File

@ -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

33
src/bubble_sort.c Normal file
View File

@ -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--;
}
}

19
src/include/bubble_sort.h Normal file
View File

@ -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

22
src/include/timer.h Normal file
View File

@ -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

View File

@ -17,9 +17,13 @@
#include <stdlib.h> #include <stdlib.h>
#include <getopt.h> #include <getopt.h>
#include "random.h" #include "random.h"
#include "timer.h"
#include "bubble_sort.h"
#define SORT_VERSION "1.0.0" #define SORT_VERSION "1.0.0"
static int *array;
/** /**
* Imprimir el uso del programa * 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, " -e, --elegir el usuario debe elegir los \"n\" valores de\n");
fprintf(stdout, " elementos a ordenar, sin esta opción los\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, " 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"); fprintf(stdout, " -v, --version mostrar la versión del programa\n");
} }
@ -48,15 +53,36 @@ void extra_algorithm() {
exit(2); 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 * La entrada del programa
* @param argc La cantidad de argumentos pasado al programa * @param argc La cantidad de argumentos pasado al programa
* @return Retorna el codigo de error o 0 por exito * @return Retorna el codigo de error o 0 por exito
*/ */
int main (int argc, char **argv) { int main (int argc, char **argv) {
int i; long long i;
int n = 10; int n = 10;
int elegir = 0; int elegir = 0;
int imprimir = 0;
int algoritmo = -1; int algoritmo = -1;
int opt; int opt;
int long_index = 0; int long_index = 0;
@ -69,6 +95,7 @@ int main (int argc, char **argv) {
{"selection", no_argument, 0, 's'}, {"selection", no_argument, 0, 's'},
{"n", required_argument, 0, 'n'}, {"n", required_argument, 0, 'n'},
{"elegir", no_argument, 0, 'e'}, {"elegir", no_argument, 0, 'e'},
{"imprimir", no_argument, 0, 'i'},
{"version", no_argument, 0, 'v'}, {"version", no_argument, 0, 'v'},
{0, 0, 0, 0} {0, 0, 0, 0}
}; };
@ -117,7 +144,7 @@ int main (int argc, char **argv) {
algoritmo = 5; algoritmo = 5;
break; break;
case 'n': case 'n':
n = atoi(optarg); n = atol(optarg);
if (n <= 1) { if (n <= 1) {
fprintf(stderr, "Error: n tiene que ser mayor de 1!\n"); fprintf(stderr, "Error: n tiene que ser mayor de 1!\n");
return 3; return 3;
@ -126,6 +153,9 @@ int main (int argc, char **argv) {
case 'e': case 'e':
elegir = 1; elegir = 1;
break; break;
case 'i':
imprimir = 1;
break;
case 'v': case 'v':
printf("sort versión: %s\n", SORT_VERSION); printf("sort versión: %s\n", SORT_VERSION);
return 0; return 0;
@ -136,23 +166,21 @@ int main (int argc, char **argv) {
} }
} }
if (algoritmo == -1) { if (algoritmo < 0 || algoritmo > 5) {
fprintf(stderr, "Error: No se seleccionó un algoritmo!\n"); fprintf(stderr, "Error: No se seleccionó un algoritmo valido!\n");
print_usage(); print_usage();
return 4; return 4;
} }
int array[n]; array = malloc(sizeof(int) * n);
atexit(cleanup);
// Llenar el array con valores para ordenar después // Llenar el array con valores para ordenar después
for (i = 0; i < n; i++) { for (i = 0; i < n; i++) {
if (elegir == 0) { if (elegir) {
array[i] = gen_rand(0, 100000);
}
else {
opt = 0; opt = 0;
while (opt <= 1) { while (opt <= 1) {
fprintf(stdout, "Elegir elemento %d: ", i + 1); fprintf(stdout, "Elegir elemento %lli: ", i + 1);
fscanf(stdin, "%d", &opt); fscanf(stdin, "%d", &opt);
if (opt <= 1) { if (opt <= 1) {
fprintf(stdout, "Número invalido! Tiene que ser mayor de 1!\n"); 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; 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; return 0;
} }

67
src/timer.c Normal file
View File

@ -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 <stdio.h>
#include <time.h>
#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);
}

15
test/Makefile Normal file
View File

@ -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

116
test/test.c Normal file
View File

@ -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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#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;
}
}