Merge branch 'fgets' of UBB/sort into master

pull/15/head
Chris Cromer 4 years ago committed by Gitea
commit fa78806865
  1. 41
      src/sort.c

@ -65,6 +65,34 @@ void print_array(int *array, int n) {
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**));
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
*/
@ -177,9 +205,7 @@ int main (int argc, char **argv) {
if (elegir) {
opt = 0;
fprintf(stdout, "Elegir elemento %lli: ", i + 1);
while (!fscanf(stdin, "%d", &opt)) {
// Falló, pide de nuevo después de limpiar stdin
while ((opt = getchar()) != '\n' && opt != EOF) { }
while (!read_buffer(&opt)) {
fprintf(stdout, "Número invalido! Tiene que ser mayor de 1!\n");
fprintf(stdout, "Elegir elemento %lli: ", i + 1);
}
@ -195,22 +221,24 @@ int main (int argc, char **argv) {
}
if (quick) {
fprintf(stdout, "Quick sort corriendo...\n");
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...\n");
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();
}
@ -219,12 +247,13 @@ int main (int argc, char **argv) {
}
if (count) {
fprintf(stdout, "Count sort corriendo...\n");
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();
}

Loading…
Cancel
Save