Commit | Line | Data |
---|---|---|
e4001676 JB |
1 | #include <stdlib.h> |
2 | ||
884e9557 | 3 | #include "array.h" |
e4001676 | 4 | |
34f864c6 JB |
5 | int* create_tab(int tab[], unsigned tab_size) { |
6 | tab = malloc(sizeof(int) * tab_size); | |
e4001676 | 7 | if (tab == NULL) { |
34f864c6 | 8 | return NULL; |
e4001676 | 9 | } else { |
34f864c6 JB |
10 | /* initialize to zero the integer array */ |
11 | for (unsigned i = 0; i < tab_size; i++) { | |
12 | tab[i] = 0; | |
13 | } | |
14 | return tab; | |
e4001676 JB |
15 | } |
16 | } | |
17 | ||
18 | void free_tab(int tab[]) { | |
19 | free(tab); | |
20 | } | |
21 | ||
34f864c6 JB |
22 | /* we suppose both tabs are already created */ |
23 | static void copy_tab(int src_tab[], int dest_tab[], unsigned src_tab_size, unsigned index_offset) { | |
24 | /* FIXME: I think it's worth doing some sanity checks on the array size: | |
25 | * dest_tab_size >= src_tab_size */ | |
26 | for (unsigned i = 0; i < src_tab_size; i++) { | |
e4001676 JB |
27 | dest_tab[i + index_offset] = src_tab[i]; |
28 | } | |
29 | } | |
30 | ||
34f864c6 JB |
31 | int* concat_tab(int tab1[], unsigned tab_size1, int tab2[], unsigned tab_size2, int tab_dest[]) { |
32 | int* rt = create_tab(tab_dest, tab_size1 + tab_size2); | |
e4001676 JB |
33 | |
34 | copy_tab(tab1, tab_dest, tab_size1, 0); | |
35 | copy_tab(tab2, tab_dest, tab_size2, tab_size1); | |
36 | return rt; | |
37 | } | |
38 | ||
34f864c6 JB |
39 | int* resize_tab(int tab[], unsigned new_tab_size) { |
40 | tab = realloc(tab, sizeof(int) * new_tab_size); | |
e4001676 | 41 | if (tab == NULL) { |
34f864c6 | 42 | return NULL; |
e4001676 | 43 | } else { |
34f864c6 | 44 | return tab; |
e4001676 JB |
45 | } |
46 | } | |
47 | ||
48 | /* number of occurences of an element in an unsorted array */ | |
49 | int count_tab_element(int tab[], unsigned tab_size, int element) { | |
50 | unsigned el_count = 0; | |
51 | for (unsigned i = 0; i < tab_size; i++) { | |
52 | if (tab[i] == element) { | |
53 | el_count++; | |
54 | } | |
55 | } | |
56 | return el_count; | |
57 | } | |
58 | ||
59 | void sort_tab(int tab[], unsigned tab_size, criteria_cb criteria) { | |
60 | sort_bubble_array(tab, tab_size, criteria); | |
61 | } |