Пример #1
0
/**
 * Adjusts heap to maintain the heap property.
 * @param heap
 * @param last  index to adjust up to.
 * @param position  index where adjustment starts.
 * @param compare  pointer to compare function.
 */
void adjustHeap(DynamicArray* heap, int last, int position, compareFunction compare)
{


int leftChild = 2 * position + 1; 
int rightChild = 2 * position + 2;
int smallestChild;
/* we have two children */
if (rightChild < last) { 
if (compare(dyGet(heap, leftChild), dyGet(heap,rightChild)) == -1)
 	 smallestChild = leftChild;
else
	 smallestChild = rightChild;
//get index of smallest child


    if (compare(dyGet(heap, position), dyGet(heap, smallestChild)) == 1) {
	dySwap(heap, position, smallestChild);
	adjustHeap(heap, last, smallestChild, compare);
}
}

else if (leftChild < last) { 
if (compare(dyGet(heap, position), dyGet(heap, leftChild)) == 1) {
dySwap(heap, position, leftChild);
adjustHeap(heap, last, leftChild, compare);
}
}
}
Пример #2
0
void shuffle(DynamicArray* array)
{
    for (int i = 0; i < dySize(array); i++)
    {
        int j = rand() % dySize(array);
        dySwap(array, i, j);
    }
}
Пример #3
0
void dyAddAt(DynamicArray* array, TYPE value, int position)
{
    assert(position <= array->size);
    dyAdd(array, value);
	int i;
    for (i = array->size - 1; i > position; i--)
    {
        dySwap(array, i, i - 1);
    }
}
Пример #4
0
/**
 * Adds an element to the heap.
 * @param heap
 * @param value  value to be added to heap.
 * @param compare  pointer to compare function.
 */
void dyHeapAdd(DynamicArray* heap, TYPE value, compareFunction compare)
{
    
//int pos = dySize(heap) - 1;

dyAdd(heap, value);
int pos = dySize(heap) - 1;
int parent;
while (pos > 0) {
    parent = (pos - 1) / 2;
    if(compare(dyGet(heap, pos), dyGet(heap, parent)) == -1){
        dySwap(heap, pos, parent);
        pos = parent;
    }

    else
        break;
}

}