sort/src/sort.c

292 líneas
7.9 KiB
C

/*
* 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 <getopt.h>
#include <string.h>
#include "random.h"
#include "timer.h"
#include "bubble_sort.h"
#include "count_sort.h"
#include "quick_sort.h"
#include "merge_sort.h"
#define SORT_VERSION "1.0.0"
/**
* El array a ordenar
*/
static int *unordered_array;
static int *work_array;
/**
* 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");
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");
fprintf(stdout, " -v, --version mostrar la versión del programa\n");
}
/**
* 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");
}
/**
* 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) {
char buffer[12];
while (1) {
if (fgets(buffer, 12, stdin) != NULL) {
if (buffer[strlen(buffer) - 1] == '\n') {
buffer[strlen(buffer) - 1] = '\0';
break;
}
}
}
char **check = malloc(sizeof(char**));
if (check == NULL) {
fprintf(stderr, "Error: Out of heap space!\n");
exit(5);
}
long input = strtol(buffer, check, 10);
if (*check[0] == '\0') {
free(check);
*variable = (int) input;
return 1;
}
else {
free(check);
return 0;
}
}
/**
* Liberar la memoria al salir
*/
void cleanup() {
free(unordered_array);
free(work_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) {
long long i;
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;
int opt;
int long_index = 0;
static struct option long_options[] = {
{"all", no_argument, 0, 'a'},
{"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'},
{"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) {
switch (opt) {
case 'a':
merge = 1;
quick = 1;
bubble = 1;
bitonic = 1;
count = 1;
selection = 1;
break;
case 'm':
merge = 1;
break;
case 'q':
quick = 1;
break;
case 'b':
bubble = 1;
break;
case 'B':
bitonic = 1;
break;
case 'c':
count = 1;
break;
case 's':
selection = 1;
break;
case 'n':
n = atol(optarg);
if (n <= 1) {
fprintf(stderr, "Error: n tiene que ser mayor de 1!\n");
return 3;
}
break;
case 'e':
elegir = 1;
break;
case 'i':
imprimir = 1;
break;
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);
if (unordered_array == NULL) {
fprintf(stderr, "Error: Out of heap space!\n");
exit(5);
}
work_array = malloc(sizeof(int) * n);
if (work_array == NULL) {
fprintf(stderr, "Error: Out of heap space!\n");
exit(5);
}
atexit(cleanup);
// Llenar el array con valores para ordenar después
for (i = 0; i < n; i++) {
if (elegir) {
opt = 0;
fprintf(stdout, "Elegir elemento %lli: ", i + 1);
while (!read_buffer(&opt)) {
fprintf(stdout, "Número invalido! Tiene que ser mayor de 1!\n");
fprintf(stdout, "Elegir elemento %lli: ", i + 1);
}
unordered_array[i] = opt;
}
else {
unordered_array[i] = gen_rand((n * 10) * -1, n * 10);
}
}
if (merge) {
fprintf(stdout, "Merge sort corriendo... ");
fflush(stdout);
memcpy(work_array, unordered_array, sizeof(int) * n);
start_timer();
merge_sort(work_array, n);
stop_timer();
fprintf(stdout, "done\n");
print_timer();
}
if (quick) {
fprintf(stdout, "Quick sort corriendo... ");
fflush(stdout);
memcpy(work_array, unordered_array, sizeof(int) * n);
start_timer();
quick_sort(work_array, n);
stop_timer();
fprintf(stdout, "done\n");
print_timer();
}
if (bubble) {
fprintf(stdout, "Bubble sort corriendo... ");
fflush(stdout);
memcpy(work_array, unordered_array, sizeof(int) * n);
start_timer();
bubble_sort(work_array, n);
stop_timer();
fprintf(stdout, "done\n");
print_timer();
}
if (bitonic) {
// bitonic sort
}
if (count) {
fprintf(stdout, "Count sort corriendo... ");
fflush(stdout);
memcpy(work_array, unordered_array, sizeof(int) * n);
start_timer();
count_sort(work_array, n);
stop_timer();
fprintf(stdout, "done\n");
print_timer();
}
if (selection) {
// selection sort
}
if (imprimir) {
fprintf(stdout, "\nAntes:\n");
print_array(unordered_array, n);
fprintf(stdout, "\nDespués:\n");
print_array(work_array, n);
}
return 0;
}