-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathint_list.c
114 lines (97 loc) · 2.09 KB
/
int_list.c
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include "int_list.h"
#include <stdio.h>
#include <stdlib.h>
int_list* new_int_list(int max) {
int_list *l = malloc(sizeof(int_list));
if (l == NULL)
return NULL;
l->ns = malloc(max * sizeof(int));
if (l->ns == NULL) {
free(l);
return NULL;
}
l->curr_len = 0;
l->max_len = max;
return l;
}
void free_int_list(int_list *ls) {
free(ls->ns);
free(ls);
}
void clear_int_list(int_list *ls) {
for (int i = 0;i < ls->curr_len;i++) {
ls->ns[i] = 0;
}
ls->curr_len = 0;
}
void print_int_list(int_list *ls) {
if (ls->curr_len == 0) {
printf("()");
return;
}
for (int i = 0;i < ls->curr_len; i++) {
printf("%c%d%c",
i == 0 ? '(' : ' ',
i,
i == ls->curr_len - 1 ? ')' : ',');
}
}
int binary_search(int key, int_list *ls, int low, int high) {
if (low > high)
return -1;
int middle = (low + high) / 2;
if (ls->ns[middle] == key) {
return middle;
}
if (ls->ns[middle] > key) {
return binary_search(key, ls, low, middle - 1);
} else {
return binary_search(key, ls, middle + 1, high);
}
}
int index_of_highest(int key, int_list *ls, int low, int high) {
if (low > high) {
// search this area back to 0
while (high > 0 && ls->ns[high] > key)
high--;
return high;
}
int middle = (low + high) / 2;
if (ls->ns[middle] == key) {
return middle;
}
if (ls->ns[middle] > key) {
return index_of_highest(key, ls, low, middle - 1);
} else {
return index_of_highest(key, ls, middle + 1, high);
}
}
int index_of(int n, int_list *ls) {
return binary_search(n, ls, 0, ls->curr_len - 1);
}
bool insert_number_sorted(int n, int_list *ls) {
// check space is left
if (ls->curr_len + 1 > ls->max_len)
return false;
int index = index_of_highest(n, ls, 0, ls->curr_len - 1);
if (index < 0) { // at start
index = 0;
} else if (index == ls->curr_len - 1) { // at end
ls->ns[index + 1] = n;
ls->curr_len++;
return true;
}
// move items across
int temp = ls->ns[index];
ls->ns[index] = n;
index++;
while (index < ls->curr_len) {
int next = ls->ns[index];
ls->ns[index] = temp;
temp = next;
index++;
}
ls->ns[index] = temp;
ls->curr_len++;
return true;
}