forked from Flyfishering/algorithmDemo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray.c
More file actions
103 lines (90 loc) · 2.07 KB
/
Copy patharray.c
File metadata and controls
103 lines (90 loc) · 2.07 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
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
//
// array.c
// algorithm
//
// Created by wangbinbin on 2019/1/10.
// Copyright © 2019 wangbinbin. All rights reserved.
//
#include "array.h"
#include <stdlib.h>
#include <string.h>
struct array {
int size;
int used;
int *arr;
};
// 打印数组
void dump(struct array *array)
{
int idx;
for (idx = 0; idx < array->used; idx++)
printf("[%02d]: %08d\n", idx, array->arr[idx]);
}
// 初始化数组
void alloc(struct array *array)
{
array->arr = (int *)malloc(array->size * sizeof(int));
}
// 插入并排序
int insert(struct array *array, int elem)
{
int idx;
if (array->used >= array->size)
return -1;
for (idx = 0; idx < array->used; idx++) {
if (array->arr[idx] > elem)
break;
}
if (idx < array->used)
memmove(&array->arr[idx+1], &array->arr[idx],
(array->used - idx) * sizeof(int));
array->arr[idx] = elem;
array->used++;
return idx;
}
// 删除元素
int delete(struct array *array, int idx)
{
if (idx < 0 || idx >= array->used)
return -1;
memmove(&array->arr[idx], &array->arr[idx+1],
(array->used - idx) * sizeof(int));
array->used--;
return 0;
}
// 查找 元素
int search(struct array *array, int elem)
{
int idx;
for (idx = 0; idx < array->used; idx++) {
if (array->arr[idx] == elem)
return idx;
if (array->arr[idx] > elem)
return -1;
}
return -1;
}
int testArr()
{
int idx;
struct array ten_int = {10, 0, NULL};
alloc(&ten_int);
if (!ten_int.arr)
return -1;
insert(&ten_int, 1);
insert(&ten_int, 3);
insert(&ten_int, 2);
printf("=== insert 1, 3, 2\n");
dump(&ten_int);
idx = search(&ten_int, 2);
printf("2 is at position %d\n", idx);
idx = search(&ten_int, 9);
printf("9 is at position %d\n", idx);
printf("=== delete [6] element \n");
delete(&ten_int, 6);
dump(&ten_int);
printf("=== delete [0] element \n");
delete(&ten_int, 0);
dump(&ten_int);
return 0;
}