Remove some unneeded 'exit 0' from bash scripts
[lcapit-junk-code.git] / bubble-sort.c
blob45bfadb7ade3a0646ca30c678665e23c269c8d07
1 /*
2 * bubble-sort: there's no reason to this for anything.
3 *
4 * Luiz Fernando N. Capitulino <lcapitulino@mandriva.com.br>
5 */
6 #include <stdio.h>
7 #include <string.h>
8 #include <stdlib.h>
10 int compare(const void *key1, const void *key2)
12 if (*((const long *) key1) > *((const long *) key2))
13 return 1;
14 else if (*((const long *) key1) < *((const long *) key2))
15 return -1;
16 else
17 return 0;
20 int bubble_sort(void *data, int size, int esize,
21 int (*compare) (const void *key1, const void *key2))
23 void *tmp;
24 char *a = data;
26 tmp = (char *) malloc(esize);
27 if (!tmp)
28 return -1;
30 for (;;) {
31 int i, has_swapped = 0;
33 for (i = 0; i < size-1; i++) {
34 if (compare(&a[i * esize], &a[(i + 1) * esize]) > 0) {
35 memcpy(tmp, &a[i * esize], esize);
36 memcpy(&a[i * esize], &a[(i + 1) * esize],
37 esize);
38 memcpy(&a[(i + 1) * esize], tmp, esize);
39 has_swapped = 1;
43 if (!has_swapped)
44 break;
47 free(tmp);
48 return 0;
51 int main(int argc, char *argv[])
53 int ret;
54 long *nums;
55 size_t len;
56 unsigned int i;
58 if (argc == 1) {
59 printf("Usage: bubble-sort <num1> <num2> ... <numN>\n");
60 exit(1);
63 len = argc - 1;
64 nums = calloc(len, sizeof(long));
65 if (!nums) {
66 perror("calloc()");
67 exit(1);
70 for (i = 0; i < len; i++) {
71 nums[i] = strtol(argv[i + 1], (char **)NULL, 10);
72 printf("%ld ", nums[i]);
74 printf("\n");
76 ret = bubble_sort((void *) nums, len, sizeof(long), compare);
77 if (ret) {
78 perror("bubble_sort()");
79 exit(1);
82 for (i = 0; i < len; i++)
83 printf("%ld ", nums[i]);
84 printf("\n");
86 free(nums);
87 return 0;