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.

sort.c 10KB

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