Skip to content

Commit 4b1daff

Browse files
committed
Implemented an optimization for add all function in binary heap.
1 parent e9fa7c1 commit 4b1daff

File tree

2 files changed

+29
-8
lines changed

2 files changed

+29
-8
lines changed

DataStructure/Trees/Sources/BinaryHeap.c

+29-2
Original file line numberDiff line numberDiff line change
@@ -250,8 +250,35 @@ void binaryHeapInsertAll(BinaryHeap *heap, void **items, int length) {
250250
#endif
251251
}
252252

253-
for (int i = 0; i < length; i++)
254-
binaryHeapInsert(heap, items[i]);
253+
if (heap->count + length > heap->length) {
254+
heap->length = (heap->count + length) * 2;
255+
256+
heap->arr = realloc(heap->arr, sizeof(void *) * heap->length);
257+
if (heap->arr == NULL) {
258+
fprintf(stderr, FAILED_REALLOCATION_MESSAGE, "heap array", "binary heap data structure");
259+
exit(FAILED_REALLOCATION);
260+
}
261+
262+
}
263+
264+
for (int i = 0; i < length; i++) {
265+
266+
if (items[i] == NULL) {
267+
#ifdef C_DATASTRUCTURES_ERRORSTESTSTRUCT_H
268+
ERROR_TEST->errorCode = INVALID_ARG;
269+
return;
270+
#else
271+
fprintf(stderr, INVALID_ARG_MESSAGE, "item pointer", "binary heap data structure");
272+
exit(INVALID_ARG);
273+
#endif
274+
}
275+
276+
heap->arr[heap->count++] = items[i];
277+
278+
}
279+
280+
for (int i = binaryHeapGetSize(heap) - 1; i >= 0; i--)
281+
binaryHeapDown(heap->arr, i, heap->count, heap->cmp);
255282

256283
}
257284

Unit Test/Tests/DataStructuresTests/TreesTest/BinaryHeapTest/BinaryHeapTest.c

-6
Original file line numberDiff line numberDiff line change
@@ -164,12 +164,6 @@ void testBinaryHeapInsertAll(CuTest *cuTest) {
164164
CuAssertIntEquals(cuTest, 1, isValidBinaryHeap(maxHeap->arr, 0, maxHeap->count, maxHeap->cmp));
165165
CuAssertIntEquals(cuTest, 1, isValidBinaryHeap(minHeap->arr, 0, minHeap->count, minHeap->cmp));
166166

167-
for (int i = 0; i < 10; i++) {
168-
CuAssertIntEquals(cuTest, maxHeapValues[i], *(int *) maxHeap->arr[i]);
169-
CuAssertIntEquals(cuTest, minHeapValues[i], *(int *) minHeap->arr[i]);
170-
}
171-
172-
173167
free(maxHeapValuesArr);
174168
free(minHeapValuesArr);
175169
destroyBinaryHeap(maxHeap);

0 commit comments

Comments
 (0)