sort/src/sort.c

378 lines
9.8 KiB
C
Raw Normal View History

2018-11-05 10:46:49 -03:00
/*
* 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.
*/
2018-11-06 12:57:38 -03:00
#include <stdio.h>
2018-11-11 13:27:38 -03:00
#include <stdlib.h>
#include <getopt.h>
2018-11-12 18:29:51 -03:00
#include <string.h>
2018-11-16 13:25:47 -03:00
#include <errno.h>
#include <limits.h>
2018-11-11 13:27:38 -03:00
#include "random.h"
#include "timer.h"
#include "bubble_sort.h"
2018-11-13 09:15:33 -03:00
#include "count_sort.h"
2018-11-13 11:59:21 -03:00
#include "quick_sort.h"
2018-11-16 09:41:22 -03:00
#include "bitonic_sort.h"
#include "selection_sort.h"
2018-11-14 17:53:45 -03:00
#include "merge_sort.h"
2018-11-11 13:27:38 -03:00
#define SORT_VERSION "1.0.0"
2018-11-06 12:57:38 -03:00
2018-11-13 09:18:03 -03:00
/**
2018-11-16 13:25:47 -03:00
* El array desordenado
2018-11-13 09:18:03 -03:00
*/
static int *unordered_array;
2018-11-16 13:25:47 -03:00
/**
* El array a ordenar
*/
static int *work_array;
2018-11-11 18:07:23 -03:00
2018-11-06 12:57:38 -03:00
/**
* Imprimir el uso del programa
*/
void print_usage() {
fprintf(stdout, "uso: sort [OPCIÓN]\n");
fprintf(stdout, " -a, --all usar todos los algoritmos de ordenamentio\n");
2018-11-06 12:57:38 -03:00
fprintf(stdout, " -m, --merge usar merge sort\n");
fprintf(stdout, " -q, --quick usar quick sort\n");
fprintf(stdout, " -b, --bubble usar bubble sort\n");
fprintf(stdout, " -B, --bitonic usar bitonic sort\n");
fprintf(stdout, " -c, --count usar ordenamiento por conteo\n");
fprintf(stdout, " -s, --selection usar ordenamiento por selección\n");
fprintf(stdout, " -n, --n=N la cantidad de elementos a ordenar, la\n");
fprintf(stdout, " cantidad predeterminado es 10\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, " valores son elegido por el programa al azar\n");
fprintf(stdout, " -i, --imprimir imprimir el array antes y despues de ordenar\n");
2018-11-06 13:05:11 -03:00
fprintf(stdout, " -v, --version mostrar la versión del programa\n");
2018-11-06 12:57:38 -03:00
}
/**
* 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\n");
}
2018-11-12 18:29:51 -03:00
/**
* Leer el buffer de stdin y guardar el valor si es numerico
* @param variable Donde se guarda el valor del stdin
* @return Retorna 1 si es exitosa ó 0 si falla
*/
int read_buffer(int *variable) {
2018-11-16 13:25:47 -03:00
char buffer[32];
char *check;
2018-11-12 18:29:51 -03:00
while (1) {
2018-11-16 13:25:47 -03:00
if (fgets(buffer, 32, stdin) != NULL) {
2018-11-12 18:29:51 -03:00
if (buffer[strlen(buffer) - 1] == '\n') {
buffer[strlen(buffer) - 1] = '\0';
break;
}
}
}
2018-11-16 13:25:47 -03:00
errno = 0;
long input = strtol(buffer, &check, 10);
if (buffer == check) {
// Empty
return 0;
}
else if (errno == ERANGE && input == LONG_MIN) {
// Overflow
return 0;
}
else if (errno == ERANGE && input == LONG_MAX) {
// Underflow
return 0;
}
else if (errno == EINVAL) { /* not in all c99 implementations - gcc OK */
// Base contains unsupported value
// This check is not in all c99 implementations, but does exist in gcc
return 0;
}
else if (errno != 0 && input == 0) {
// Unspecified error
return 0;
2018-11-14 16:21:26 -03:00
}
2018-11-16 13:25:47 -03:00
else if (errno == 0 && !*check) {
// Valid number
if (input > INT_MAX || input < INT_MIN) {
fprintf(stderr, "Error: n tiene que ser menor de 2147483648 y mayor de -2147483649!\n");
return 0;
}
2018-11-12 18:29:51 -03:00
*variable = (int) input;
return 1;
}
2018-11-16 13:25:47 -03:00
else if (errno == 0 && *check != 0) {
// Contains non number characters
return 0;
}
2018-11-12 18:29:51 -03:00
else {
return 0;
}
}
2018-11-16 13:25:47 -03:00
/**
* Imprimir un mensaje y salir si n es invalido
*/
void print_invalid_n() {
fprintf(stderr, "Error: El valor de n es invalido!\n");
exit(7);
}
2018-11-17 13:35:31 -03:00
/**
* Empezar los pasos antes de ordenar
*/
void start_sort(const char *message, int n) {
fprintf(stdout, "%s", message);
fflush(stdout);
memcpy(work_array, unordered_array, sizeof(int) * n);
start_timer();
}
/**
* Empezar los pasos después de ordenar
*/
void end_sort() {
stop_timer();
fprintf(stdout, "done\n");
print_timer();
fprintf(stdout, "\n");
}
/**
* Liberar la memoria al salir
*/
2018-11-11 18:07:23 -03:00
void cleanup() {
free(unordered_array);
free(work_array);
2018-11-11 18:07:23 -03:00
}
2018-11-06 12:57:38 -03:00
/**
* La entrada del programa
* @param argc La cantidad de argumentos pasado al programa
2018-11-11 13:27:38 -03:00
* @return Retorna el codigo de error o 0 por exito
2018-11-06 12:57:38 -03:00
*/
2018-11-05 10:46:49 -03:00
int main (int argc, char **argv) {
2018-11-16 13:25:47 -03:00
char *check = NULL;
long ninput = 0;
int i;
2018-11-11 13:27:38 -03:00
int n = 10;
int elegir = 0;
int imprimir = 0;
int merge = 0;
int quick = 0;
int bubble = 0;
int bitonic = 0;
int count = 0;
int selection = 0;
2018-11-11 13:27:38 -03:00
int opt;
int long_index = 0;
static struct option long_options[] = {
{"all", no_argument, 0, 'a'},
2018-11-11 13:27:38 -03:00
{"merge", no_argument, 0, 'm'},
{"quick", no_argument, 0, 'q'},
{"bubble", no_argument, 0, 'b'},
{"bitonic", no_argument, 0, 'B'},
{"count", no_argument, 0, 'c'},
{"selection", no_argument, 0, 's'},
{"n", required_argument, 0, 'n'},
{"elegir", no_argument, 0, 'e'},
{"imprimir", no_argument, 0, 'i'},
2018-11-11 13:27:38 -03:00
{"version", no_argument, 0, 'v'},
{0, 0, 0, 0}
};
if (argc == 1) {
print_usage();
return 0;
}
while ((opt = getopt_long(argc, argv, "amqbBcsn:eiv", long_options, &long_index)) != -1) {
2018-11-11 13:27:38 -03:00
switch (opt) {
case 'a':
merge = 1;
quick = 1;
bubble = 1;
bitonic = 1;
count = 1;
selection = 1;
break;
2018-11-11 13:27:38 -03:00
case 'm':
merge = 1;
2018-11-11 13:27:38 -03:00
break;
case 'q':
quick = 1;
2018-11-11 13:27:38 -03:00
break;
case 'b':
bubble = 1;
2018-11-11 13:27:38 -03:00
break;
case 'B':
bitonic = 1;
2018-11-11 13:27:38 -03:00
break;
case 'c':
count = 1;
2018-11-11 13:27:38 -03:00
break;
case 's':
selection = 1;
2018-11-11 13:27:38 -03:00
break;
case 'n':
2018-11-16 13:25:47 -03:00
errno = 0;
ninput = strtol(optarg, &check, 10);
if (optarg == check) {
// Empty
print_invalid_n();
}
else if (errno == ERANGE && ninput == LONG_MIN) {
// Overflow
print_invalid_n();
}
else if (errno == ERANGE && ninput == LONG_MAX) {
// Underflow
print_invalid_n();
}
else if (errno == EINVAL) { /* not in all c99 implementations - gcc OK */
// Base contains unsupported value
// This check is not in all c99 implementations, but does exist in gcc
print_invalid_n();
}
else if (errno != 0 && ninput == 0) {
// Unspecified error
print_invalid_n();
}
else if (errno == 0 && optarg && !*check) {
// Valid number
if (ninput > INT_MAX || ninput < INT_MIN) {
fprintf(stderr, "Error: n tiene que ser menor de 2147483648!\n");
return 6;
}
n = (int) ninput;
if (n <= 1) {
fprintf(stderr, "Error: n tiene que ser mayor de 1!\n");
return 3;
}
}
else if (errno == 0 && optarg && *check != 0) {
// Contains non number characters
print_invalid_n();
2018-11-11 13:27:38 -03:00
}
break;
case 'e':
elegir = 1;
break;
case 'i':
imprimir = 1;
break;
2018-11-11 13:27:38 -03:00
case 'v':
printf("sort versión: %s\n", SORT_VERSION);
return 0;
break;
default:
print_usage();
return 1;
}
}
if (!merge && !quick && !bubble && !bitonic && !count && !selection) {
fprintf(stderr, "Error: No se seleccionó un algoritmo valido!\n");
print_usage();
return 4;
}
unordered_array = malloc(sizeof(int) * n);
2018-11-14 16:21:26 -03:00
if (unordered_array == NULL) {
2018-11-14 20:17:41 -03:00
fprintf(stderr, "Error: Out of heap space!\n");
2018-11-14 16:21:26 -03:00
exit(5);
}
work_array = malloc(sizeof(int) * n);
2018-11-14 16:21:26 -03:00
if (work_array == NULL) {
2018-11-14 20:17:41 -03:00
fprintf(stderr, "Error: Out of heap space!\n");
2018-11-14 16:21:26 -03:00
exit(5);
}
2018-11-11 18:07:23 -03:00
atexit(cleanup);
2018-11-11 13:27:38 -03:00
// Llenar el array con valores para ordenar después
for (i = 0; i < n; i++) {
if (elegir) {
2018-11-11 13:27:38 -03:00
opt = 0;
2018-11-16 13:25:47 -03:00
fprintf(stdout, "Elegir elemento %d: ", i + 1);
2018-11-12 18:29:51 -03:00
while (!read_buffer(&opt)) {
2018-11-16 13:25:47 -03:00
fprintf(stdout, "Número invalido! Tiene que ser mayor de -2147483649 y menor de 2147483648!\n");
fprintf(stdout, "Elegir elemento %d: ", i + 1);
2018-11-11 13:27:38 -03:00
}
unordered_array[i] = opt;
2018-11-11 13:27:38 -03:00
}
else {
2018-11-16 13:25:47 -03:00
unordered_array[i] = gen_rand(-100000000, 100000000);
}
2018-11-11 13:27:38 -03:00
}
// O(nlog(n))
if (quick) {
2018-11-17 13:35:31 -03:00
start_sort("Quick sort corriendo... ", n);
2018-11-13 12:20:01 -03:00
quick_sort(work_array, n);
2018-11-17 13:35:31 -03:00
end_sort();
}
// O(nlog(n))
if (merge) {
start_sort("Merge sort corriendo... ", n);
merge_sort(work_array, n);
2018-11-17 13:35:31 -03:00
end_sort();
}
// O(nlog2(n))
if (bitonic) {
2018-11-17 13:35:31 -03:00
start_sort("Bitonic sort corriendo... ", n);
2018-11-16 09:41:22 -03:00
bitonic_sort(work_array, n);
2018-11-17 13:35:31 -03:00
end_sort();
}
// O(n+k)
if (count) {
2018-11-17 13:35:31 -03:00
start_sort("Count sort corriendo... ", n);
count_sort(work_array, n);
2018-11-17 13:35:31 -03:00
end_sort();
}
// O(n^2)
if (bubble) {
start_sort("Bubble sort corriendo... ", n);
bubble_sort(work_array, n);
end_sort();
}
// O(n^2)
if (selection) {
2018-11-17 13:35:31 -03:00
start_sort("Selection sort corriendo... ", n);
2018-11-16 09:41:22 -03:00
selection_sort(work_array, n);
2018-11-17 13:35:31 -03:00
end_sort();
}
if (imprimir) {
2018-11-17 13:35:31 -03:00
fprintf(stdout, "Antes:\n");
print_array(unordered_array, n);
2018-11-17 13:35:31 -03:00
fprintf(stdout, "Después:\n");
print_array(work_array, n);
}
2018-11-05 10:46:49 -03:00
return 0;
}