我尝试使用动态数组在C中创建一个简单的Set抽象数据类型,仅用于学习目的。我实现了一个名为buildSet()
的函数,它将结构Set
作为参数,n
元素 - 参数后面要导入的元素的数量n
。我的问题是我不应该允许重复值,正如我们从数学中知道的那样。但我的代码无法通过此要求。我没有错误地实现了Set结构,但是当我去打印我的设置时,我看到存在重复。
考虑以下示例
在主文件中:
Set S;
buildSet(&S, 6, 5, 20, 2, 3, -8, -8);
for (int i = 0; i < S.size; ++i) {
printf("%d ", S.elems[i]);
}
预期输出
5 20 2 3 -8
实际输出是
5 20 2 3 -8 -8
贝娄是我使用的结构:
typedef struct {
int *elems; /* Array contains our set elements. */
size_t size; /* Number of elements exist in set. */
long maxSize; /* Maximum allowed number of elements in set. */
long sum; /* Sum of all elements in set. */
int *min; /* The minimum element in set. */
int *max; /* The maximum element in set. */
} Set;
我使用的函数原型:
/**
* Creates a set structure S
* with n elements x1,x2, x3,….
*/
void buildSet(Set *S, size_t n, ...);
/**
* Checks whether the value x is in the set S.
*/
int isElementOfSet(Set *S, int x);
贝娄是功能体:
void buildSet(Set *S, size_t n, ...) {
/**
* Pass each argument, representing a set element,
* from our variadic function to variadic list.
*/
va_list setElems;
/**
* Get the number of elements we want to pass
* to our set.
*/
va_start(setElems, n);
/**
* The number of elements in set structure.
*/
S->size = 0;
/**
* Using this function we don't restrict ourselves
* of using any number of elements for our set, so
* we "unset" maxSize member.
*/
S->maxSize = -1;
/**
* We initialize the sum counter. This will
* allow us to get the sum using sumOfSet()
* in O(1) time.
*/
S->sum = 0;
/**
* Allocates memory for our set.
*/
S->elems = malloc(sizeof(int)*(S->size));
/**
* Pass each set element, to our set
* and update the sum counter.
*/
int elem;
for (size_t i = 0; i < n; ++i) {
elem = va_arg(setElems, int);
if (!isElementOfSet(S, elem)) {
++(S->size);
S->elems = realloc(S->elems, sizeof(int)*(S->size));
S->elems[(S->size)-1] = elem;
S->sum += elem;
}
}
/**
* Frees the variadic list.
*/
va_end(setElems);
}
int isElementOfSet(Set *S, int x) {
/**
* We use binary search in our array-set
* to find if x belongs to S.
*/
int middle, left = 0, right = (S->size)-1;
while (left < right) {
middle = (left + right)/2;
if (S->elems[middle] == x) {
return 1;
} else {
if (S->elems[middle] > x) {
right = middle - 1;
} else {
left = middle + 1;
}
}
}
return 0;
}
答案 0 :(得分:0)
您已在方法isElementOfSet
中使用二进制搜索。如果对该数组的元素进行排序,则 Binary Search 只能应用于数组。我没有看到你应用某种排序的任何地方。因此,我建议您将方法isElementOfSet
更改为线性搜索。
int isElementOfSet(Set *S, int x) {
int i;
for(i = 0;i < S->size;++i)
{
if(S->elems[i] == x)
return 1;
}
return 0;
}