Proyecto de ordenamiento para el curso de Análisis y Diseño de Algoritmos.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

366 lines
9.7KB

  1. /*
  2. * Copyright 2018 Christopher Cromer
  3. * Copyright 2018 Rodolfo Cuevas
  4. *
  5. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
  6. *
  7. * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  8. *
  9. * 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.
  10. *
  11. * 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.
  12. *
  13. * 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.
  14. */
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <getopt.h>
  18. #include <string.h>
  19. #include <errno.h>
  20. #include <limits.h>
  21. #include "random.h"
  22. #include "timer.h"
  23. #include "bubble_sort.h"
  24. #include "count_sort.h"
  25. #include "quick_sort.h"
  26. #include "merge_sort.h"
  27. #define SORT_VERSION "1.0.0"
  28. /**
  29. * El array desordenado
  30. */
  31. static int *unordered_array;
  32. /**
  33. * El array a ordenar
  34. */
  35. static int *work_array;
  36. /**
  37. * Imprimir el uso del programa
  38. */
  39. void print_usage() {
  40. fprintf(stdout, "uso: sort [OPCIÓN]\n");
  41. fprintf(stdout, " -a, --all usar todos los algoritmos de ordenamentio\n");
  42. fprintf(stdout, " -m, --merge usar merge sort\n");
  43. fprintf(stdout, " -q, --quick usar quick sort\n");
  44. fprintf(stdout, " -b, --bubble usar bubble sort\n");
  45. fprintf(stdout, " -B, --bitonic usar bitonic sort\n");
  46. fprintf(stdout, " -c, --count usar ordenamiento por conteo\n");
  47. fprintf(stdout, " -s, --selection usar ordenamiento por selección\n");
  48. fprintf(stdout, " -n, --n=N la cantidad de elementos a ordenar, la\n");
  49. fprintf(stdout, " cantidad predeterminado es 10\n");
  50. fprintf(stdout, " -e, --elegir el usuario debe elegir los \"n\" valores de\n");
  51. fprintf(stdout, " elementos a ordenar, sin esta opción los\n");
  52. fprintf(stdout, " valores son elegido por el programa al azar\n");
  53. fprintf(stdout, " -i, --imprimir imprimir el array antes y despues de ordenar\n");
  54. fprintf(stdout, " -v, --version mostrar la versión del programa\n");
  55. }
  56. /**
  57. * Imprimir un array
  58. * @param *array El array a imprimir
  59. * @param n La cantidad de elementos que están en el array
  60. */
  61. void print_array(int *array, int n) {
  62. int i;
  63. for (i = 0; i < n; i++) {
  64. fprintf(stdout, "%d ", array[i]);
  65. }
  66. fprintf(stdout, "\n\n");
  67. }
  68. /**
  69. * Leer el buffer de stdin y guardar el valor si es numerico
  70. * @param variable Donde se guarda el valor del stdin
  71. * @return Retorna 1 si es exitosa ó 0 si falla
  72. */
  73. int read_buffer(int *variable) {
  74. char buffer[32];
  75. char *check;
  76. while (1) {
  77. if (fgets(buffer, 32, stdin) != NULL) {
  78. if (buffer[strlen(buffer) - 1] == '\n') {
  79. buffer[strlen(buffer) - 1] = '\0';
  80. break;
  81. }
  82. }
  83. }
  84. errno = 0;
  85. long input = strtol(buffer, &check, 10);
  86. if (buffer == check) {
  87. // Empty
  88. return 0;
  89. }
  90. else if (errno == ERANGE && input == LONG_MIN) {
  91. // Overflow
  92. return 0;
  93. }
  94. else if (errno == ERANGE && input == LONG_MAX) {
  95. // Underflow
  96. return 0;
  97. }
  98. else if (errno == EINVAL) { /* not in all c99 implementations - gcc OK */
  99. // Base contains unsupported value
  100. // This check is not in all c99 implementations, but does exist in gcc
  101. return 0;
  102. }
  103. else if (errno != 0 && input == 0) {
  104. // Unspecified error
  105. return 0;
  106. }
  107. else if (errno == 0 && !*check) {
  108. // Valid number
  109. if (input > INT_MAX || input < INT_MIN) {
  110. fprintf(stderr, "Error: n tiene que ser menor de 2147483648 y mayor de -2147483649!\n");
  111. return 0;
  112. }
  113. *variable = (int) input;
  114. return 1;
  115. }
  116. else if (errno == 0 && *check != 0) {
  117. // Contains non number characters
  118. return 0;
  119. }
  120. else {
  121. return 0;
  122. }
  123. }
  124. /**
  125. * Imprimir un mensaje y salir si n es invalido
  126. */
  127. void print_invalid_n() {
  128. fprintf(stderr, "Error: El valor de n es invalido!\n");
  129. exit(7);
  130. }
  131. /**
  132. * Liberar la memoria al salir
  133. */
  134. void cleanup() {
  135. free(unordered_array);
  136. free(work_array);
  137. }
  138. /**
  139. * La entrada del programa
  140. * @param argc La cantidad de argumentos pasado al programa
  141. * @return Retorna el codigo de error o 0 por exito
  142. */
  143. int main (int argc, char **argv) {
  144. char *check = NULL;
  145. long ninput = 0;
  146. int i;
  147. int n = 10;
  148. int elegir = 0;
  149. int imprimir = 0;
  150. int merge = 0;
  151. int quick = 0;
  152. int bubble = 0;
  153. int bitonic = 0;
  154. int count = 0;
  155. int selection = 0;
  156. int opt;
  157. int long_index = 0;
  158. static struct option long_options[] = {
  159. {"all", no_argument, 0, 'a'},
  160. {"merge", no_argument, 0, 'm'},
  161. {"quick", no_argument, 0, 'q'},
  162. {"bubble", no_argument, 0, 'b'},
  163. {"bitonic", no_argument, 0, 'B'},
  164. {"count", no_argument, 0, 'c'},
  165. {"selection", no_argument, 0, 's'},
  166. {"n", required_argument, 0, 'n'},
  167. {"elegir", no_argument, 0, 'e'},
  168. {"imprimir", no_argument, 0, 'i'},
  169. {"version", no_argument, 0, 'v'},
  170. {0, 0, 0, 0}
  171. };
  172. if (argc == 1) {
  173. print_usage();
  174. return 0;
  175. }
  176. while ((opt = getopt_long(argc, argv, "amqbBcsn:eiv", long_options, &long_index)) != -1) {
  177. switch (opt) {
  178. case 'a':
  179. merge = 1;
  180. quick = 1;
  181. bubble = 1;
  182. bitonic = 1;
  183. count = 1;
  184. selection = 1;
  185. break;
  186. case 'm':
  187. merge = 1;
  188. break;
  189. case 'q':
  190. quick = 1;
  191. break;
  192. case 'b':
  193. bubble = 1;
  194. break;
  195. case 'B':
  196. bitonic = 1;
  197. break;
  198. case 'c':
  199. count = 1;
  200. break;
  201. case 's':
  202. selection = 1;
  203. break;
  204. case 'n':
  205. errno = 0;
  206. ninput = strtol(optarg, &check, 10);
  207. if (optarg == check) {
  208. // Empty
  209. print_invalid_n();
  210. }
  211. else if (errno == ERANGE && ninput == LONG_MIN) {
  212. // Overflow
  213. print_invalid_n();
  214. }
  215. else if (errno == ERANGE && ninput == LONG_MAX) {
  216. // Underflow
  217. print_invalid_n();
  218. }
  219. else if (errno == EINVAL) { /* not in all c99 implementations - gcc OK */
  220. // Base contains unsupported value
  221. // This check is not in all c99 implementations, but does exist in gcc
  222. print_invalid_n();
  223. }
  224. else if (errno != 0 && ninput == 0) {
  225. // Unspecified error
  226. print_invalid_n();
  227. }
  228. else if (errno == 0 && optarg && !*check) {
  229. // Valid number
  230. if (ninput > INT_MAX || ninput < INT_MIN) {
  231. fprintf(stderr, "Error: n tiene que ser menor de 2147483648!\n");
  232. return 6;
  233. }
  234. n = (int) ninput;
  235. if (n <= 1) {
  236. fprintf(stderr, "Error: n tiene que ser mayor de 1!\n");
  237. return 3;
  238. }
  239. }
  240. else if (errno == 0 && optarg && *check != 0) {
  241. // Contains non number characters
  242. print_invalid_n();
  243. }
  244. break;
  245. case 'e':
  246. elegir = 1;
  247. break;
  248. case 'i':
  249. imprimir = 1;
  250. break;
  251. case 'v':
  252. printf("sort versión: %s\n", SORT_VERSION);
  253. return 0;
  254. break;
  255. default:
  256. print_usage();
  257. return 1;
  258. }
  259. }
  260. if (!merge && !quick && !bubble && !bitonic && !count && !selection) {
  261. fprintf(stderr, "Error: No se seleccionó un algoritmo valido!\n");
  262. print_usage();
  263. return 4;
  264. }
  265. unordered_array = malloc(sizeof(int) * n);
  266. if (unordered_array == NULL) {
  267. fprintf(stderr, "Error: Out of heap space!\n");
  268. exit(5);
  269. }
  270. work_array = malloc(sizeof(int) * n);
  271. if (work_array == NULL) {
  272. fprintf(stderr, "Error: Out of heap space!\n");
  273. exit(5);
  274. }
  275. atexit(cleanup);
  276. // Llenar el array con valores para ordenar después
  277. for (i = 0; i < n; i++) {
  278. if (elegir) {
  279. opt = 0;
  280. fprintf(stdout, "Elegir elemento %d: ", i + 1);
  281. while (!read_buffer(&opt)) {
  282. fprintf(stdout, "Número invalido! Tiene que ser mayor de -2147483649 y menor de 2147483648!\n");
  283. fprintf(stdout, "Elegir elemento %d: ", i + 1);
  284. }
  285. unordered_array[i] = opt;
  286. }
  287. else {
  288. unordered_array[i] = gen_rand(-100000000, 100000000);
  289. }
  290. }
  291. if (merge) {
  292. fprintf(stdout, "Merge sort corriendo... ");
  293. fflush(stdout);
  294. memcpy(work_array, unordered_array, sizeof(int) * n);
  295. start_timer();
  296. merge_sort(work_array, n);
  297. stop_timer();
  298. fprintf(stdout, "done\n");
  299. print_timer();
  300. }
  301. if (quick) {
  302. fprintf(stdout, "Quick sort corriendo... ");
  303. fflush(stdout);
  304. memcpy(work_array, unordered_array, sizeof(int) * n);
  305. start_timer();
  306. quick_sort(work_array, n);
  307. stop_timer();
  308. fprintf(stdout, "done\n");
  309. print_timer();
  310. }
  311. if (bubble) {
  312. fprintf(stdout, "Bubble sort corriendo... ");
  313. fflush(stdout);
  314. memcpy(work_array, unordered_array, sizeof(int) * n);
  315. start_timer();
  316. bubble_sort(work_array, n);
  317. stop_timer();
  318. fprintf(stdout, "done\n");
  319. print_timer();
  320. }
  321. if (bitonic) {
  322. // bitonic sort
  323. }
  324. if (count) {
  325. fprintf(stdout, "Count sort corriendo... ");
  326. fflush(stdout);
  327. memcpy(work_array, unordered_array, sizeof(int) * n);
  328. start_timer();
  329. count_sort(work_array, n);
  330. stop_timer();
  331. fprintf(stdout, "done\n");
  332. print_timer();
  333. }
  334. if (selection) {
  335. // selection sort
  336. }
  337. if (imprimir) {
  338. fprintf(stdout, "\nAntes:\n");
  339. print_array(unordered_array, n);
  340. fprintf(stdout, "\nDespués:\n");
  341. print_array(work_array, n);
  342. }
  343. return 0;
  344. }