-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharray.c
53 lines (52 loc) · 1.17 KB
/
array.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
#include <stdlib.h>
#include <stdio.h>
struct Arr {
int data[10000000];
int tail;
};
struct Arr* arr_insert(struct Arr* arr, int target) {
struct Arr* ptr;
if (!arr) {
ptr = (struct Arr*)malloc(sizeof(struct Arr));
ptr->data[0] = target;
ptr->tail = 1;
return ptr;
}
arr->data[arr->tail] = target;
arr->tail++;
return arr;
}
int* arr_traverse_find(struct Arr* arr, int target) {
int i;
for (i = 0; i < arr->tail; i++) {
if (arr->data[i] == target) {
return &arr->data[i];
break;
}
}
return NULL;
}
int compare(const void* a, const void* b) {
return *(int*)a - *(int*)b;
}
int* arr_bs_find(struct Arr* arr, int target) {
int front, back;
int mid;
int i;
front = 0;
back = arr->tail - 1;
mid = (front + back) / 2;
while (front <= back) {
mid = (front + back) / 2;
if (target > arr->data[mid]) {
front = mid + 1;
}
else if (target < arr->data[mid]) {
back = mid - 1;
}
else if (target == arr->data[mid]) {
return &(arr->data[mid]);
}
}
return NULL;
}