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.

382 lines
10KB

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