-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathintset.c
More file actions
64 lines (56 loc) · 1.11 KB
/
intset.c
File metadata and controls
64 lines (56 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <stdlib.h>
#include <stdbool.h>
#include "intset.h"
typedef struct intset {
int *arr;
size_t length;
size_t capacity;
} intset;
intset *
intset_new()
{
intset *set = malloc(sizeof(intset));
set->arr = malloc(sizeof(int) * 10);
set->length = 0;
set->capacity = 10;
return set;
}
void
intset_free(intset *set)
{
if (set) {
free(set->arr);
free(set);
}
}
static int
intset_cmp(const void *a, const void *b)
{
int x = *(int *)a, y = *(int *)b;
if (x < y) {
return -1;
} else if (x > y) {
return 1;
}
return 0;
}
void
intset_add(intset *set, int item)
{
if (intset_contains(set, item)) {
return;
}
if (set->length + 1 > set->capacity) {
set->capacity *= 2;
set->arr = realloc(set->arr, sizeof(int) * set->capacity);
}
set->arr[set->length] = item;
set->length++;
qsort(set->arr, set->length, sizeof(int), intset_cmp);
}
bool
intset_contains(intset *set, int item)
{
void *found = bsearch(&item, set->arr, set->length, sizeof(int), intset_cmp);
return found != NULL;
}