void ReplacementSelection<obj>::current_heap_push(obj entry){
	if(activeLeft){
		heap[leftEnd]=entry;
		siftUp(leftEnd,activeLeft);
	}
	else{
		heap[rightEnd]=entry;
		siftUp(rightEnd,activeLeft);
	}
}
void ReplacementSelection<obj>::pending_heap_push(obj entry){
	if(activeLeft){
		leftEnd--;
		rightEnd--;
		heap[rightEnd]=entry;
		siftUp(rightEnd,!activeLeft);
	}
	else{
		leftEnd++;
		rightEnd++;
		heap[leftEnd]=entry;
		siftUp(leftEnd,!activeLeft);
	}
}
示例#3
0
文件: heap.c 项目: jaingaurav/rstm
/* =============================================================================
 * heap_insert
 * -- Returns false on failure
 * =============================================================================
 */
bool
heap_insert (heap_t* heapPtr, void* dataPtr)
{
    long size = heapPtr->size;
    long capacity = heapPtr->capacity;

    if ((size + 1) >= capacity) {
        long newCapacity = capacity * 2;
        void** newElements = (void**)SEQ_MALLOC(newCapacity * sizeof(void*));
        if (newElements == NULL) {
            return false;
        }
        heapPtr->capacity = newCapacity;
        long i;
        void** elements = heapPtr->elements;
        for (i = 0; i <= size; i++) {
            newElements[i] = elements[i];
        }
        SEQ_FREE(heapPtr->elements);
        heapPtr->elements = newElements;
    }

    size = ++(heapPtr->size);
    heapPtr->elements[size] = dataPtr;
    siftUp(heapPtr, size);

    return true;
}
示例#4
0
void insert (queue *q, int value, double pri)
{
	unsigned int j;
	int p, newAllocated;
	item i;
	i.value = value;
	i.priority = pri;

        newAllocated = smallestPowerOfTwoAfter ((value + 1) * sizeof(int));

        if ((value + 1) * sizeof (int) > q->indexAllocated) {
		q->index = realloc (q->index, newAllocated);
		if (NULL == q->index)
			exit (1);
		for (j = q->indexAllocated / sizeof (int); j < newAllocated / sizeof (int); j++)
			q->index[j] = -1;
		q->indexAllocated = newAllocated;
	}

	p = placeAtEnd (q, i);

	q->index[q->root[p].value] = p;	

	siftUp (q, p);
}
// Prim algorithm 
void Prim(Graph G, int s){
	//perform Prims's algorithm on G starting with vertex s

	int j, heap[MaxVertices + 1], heapLoc[MaxVertices + 1];
	G->vertex[s].cost = 0;
	for (j = 1; j <= G->numV; j++) heap[j] = heapLoc[j] = j;
	heap[1] = s; heap[s] = 1; heapLoc[s] = 1; heapLoc[1] = s;
	int heapSize = G->numV;
	while (heapSize > 0)
	{
		int u = heap[1];
		if (G->vertex[u].cost == Infinity) break;
		G->vertex[u].colour = Black;
		//reorganize heap after removing top item
		siftDown(G, heap[heapSize], heap, 1, heapSize - 1, heapLoc);
		GEdgePtr p = G->vertex[u].firstEdge;
		while (p != NULL)
		{
			if (G->vertex[p->child].colour == White && p->weight < G->vertex[p->child].cost)
			{
				G->vertex[p->child].cost = p->weight;
				G->vertex[p->child].parent = u;
				siftUp(G, heap, heapLoc[p->child], heapLoc);
			}
			p = p->nextEdge;
		}
		--heapSize;
	}// end while
	printMST(G);
}// end Prim's
示例#6
0
/*This change adds an element to the heap and preseves the heap proerty, also udpates the
 *end pointer
 */
void q_add(int *q, void *te)
{
    int pos = *q;
    struct event *t = (struct event *)te;

    int i = 0;
    for(i ; i < pos; i++)
    {
        if(heap[i].timer == t->timer && heap[i].due <= t->due)
            return;
    }

    memcpy(heap+pos, t, sizeof(struct event));
    siftUp(heap, pos);


    PRINTF("The desired val %c \n", t->timer);
    PRINTF("The value %d\n", pos);
    PRINTF("1The timer val %s \n" ,(heap+pos)->timer);
    PRINTF("2The timer val %c \n" ,heap[pos].timer);
    PRINTF("2The timer val %lld\n" ,heap[pos].due);

    PRINTF("PRIO Q ADDING: timer %c, timer %lld \n" ,heap[pos].timer, heap[pos].due);
    PRINTF("PRIO Q: new position %d\n\n", pos);
    pos++;
    memcpy(q ,&(pos), sizeof(int));
}
示例#7
0
void D_HEAP<KeyType>::insert(const KeyType& node, mem_rc flag, int size) {

    switch (flag) {
    case PROHIBIT_MEMORY_REALLOCATION:
        break;
    case ALLOW_MEMORY_REALLOCATION_WCV:
        if (size_ == sizeTree_) {
            size_ += getReallocSize();
            tree_ = (KeyType*)realloc(tree_, size_ * sizeof(KeyType));
            if (tree_ == 0)
                throw myExcp("Memory allocation error.");
        }
        break;
    case ALLOW_MEMORY_REALLOCATION_WYV:
        if (size < 0)
            throw("Size must be >= 0");
        size_ += size;
        tree_ = (KeyType*)realloc(tree_, size_ * sizeof(KeyType));
        if (tree_ == 0)
            throw myExcp("Memory allocation error.");
        break;
    default:
        throw myExcp("Incorrect flag value");
    }

    if (size_ == sizeTree_)
        throw myExcp("No memory for insert node.");
    sizeTree_++;
    tree_[sizeTree_ - 1] = node;
    siftUp(sizeTree_ - 1);
}
示例#8
0
 void push(HeapElement* element)
 {
     element->setHeap(this);
     element->setIndex(heap_.size());
     heap_.push_back(element);
     siftUp(heap_.size() - 1);
 }
示例#9
0
文件: heap.c 项目: Ikulagin/transmem
/* =============================================================================
 * heap_insert
 * -- Returns FALSE on failure
 * =============================================================================
 */
TM_SAFE
bool_t
heap_insert (heap_t* heapPtr, void* dataPtr)
{
    long size = heapPtr->size;
    long capacity = heapPtr->capacity;

    if ((size + 1) >= capacity) {
        long newCapacity = capacity * 2;
        void** newElements = (void**)malloc(newCapacity * sizeof(void*));
        if (newElements == NULL) {
            return FALSE;
        }
        heapPtr->capacity = newCapacity;
        long i;
        void** elements = heapPtr->elements;
        for (i = 0; i <= size; i++) {
            newElements[i] = elements[i];
        }
        free(heapPtr->elements);
        heapPtr->elements = newElements;
    }
    size ++;
    heapPtr->size = size;
    //size = ++(heapPtr->size);
    heapPtr->elements[size] = dataPtr;
    siftUp(heapPtr, size);

    return TRUE;
}
示例#10
0
文件: heap.c 项目: Ikulagin/transmem
TM_SAFE
bool_t
TMheap_insert (  heap_t* heapPtr, void* dataPtr)
{
    long size = (long)TM_SHARED_READ(heapPtr->size);
    long capacity = (long)TM_SHARED_READ(heapPtr->capacity);

    if ((size + 1) >= capacity) {
        long newCapacity = capacity * 2;
        void** newElements = (void**)TM_MALLOC(newCapacity * sizeof(void*));
        if (newElements == NULL) {
            return FALSE;
        }
        TM_SHARED_WRITE(heapPtr->capacity, newCapacity);
        long i;
        void** elements = (void **)TM_SHARED_READ_P(heapPtr->elements);
        for (i = 0; i <= size; i++) {
            newElements[i] = (void*)TM_SHARED_READ_P(elements[i]);
        }
        free(heapPtr->elements);
        TM_SHARED_WRITE_P(heapPtr->elements, newElements);
    }

    size++;
    TM_SHARED_WRITE(heapPtr->size, size);
    void** elements = (void**)TM_SHARED_READ_P(heapPtr->elements);
    TM_SHARED_WRITE_P(elements[size], dataPtr);
    siftUp(heapPtr, size);

    return TRUE;
}
示例#11
0
int BinaryHeap_insert(BinaryHeap h, void *item){
  int len = h->len, id = len, flag, pos;

  /* insert an item, and return its ID. This ID can be used later to extract the item */
  if (len > h->max_len - 1) {
    if (BinaryHeap_realloc(h) == NULL) return BinaryHeap_error_malloc;
  }
  
  /* check if we have IDs in the stack to reuse. If no, then assign the last pos as the ID */
  id = IntStack_pop(h->id_stack, &flag);
  if (flag) id = len;

  h->heap[len] = item;
  h->id_to_pos[id] = len;
  h->pos_to_id[len] = id;

  (h->len)++;

  pos = siftUp(h, len);
  assert(h->id_to_pos[id] == pos);
  assert(h->pos_to_id[pos] == id);


  return id;
}
		void update(SteerLib::AStarPlannerNode parentNode, int xIncr, int zIncr, SteerLib::GridDatabase2D * gSpatialDatabase, Util::Point goal) {
			
			unsigned int parentX, parentZ;
			gSpatialDatabase->getGridCoordinatesFromIndex(parentNode.gridIndex, parentX, parentZ);
			int newIndex = gSpatialDatabase->getCellIndexFromGridCoords(parentX+xIncr, parentZ+zIncr);
			Util::Point newPoint;
			gSpatialDatabase->getLocationFromIndex(newIndex, newPoint);
			double newG = parentNode.g+1;
			//diagonal movement costs more (root2)
			if(DIAGMOD && zIncr != 0 && xIncr != 0) {
				newG += 0.414; //root2 rounded
			}
			SteerLib::AStarPlannerNode newNode = SteerLib::AStarPlannerNode(newPoint, newG, max-(newG+HEURISTICWEIGHT*calcHeur(newPoint, goal, false)), parentNode.gridIndex);
			newNode.gridIndex = newIndex;

			int i = 0;
			for(; i < heap.size(); i++) {
				if(heap[i].gridIndex == newNode.gridIndex) {
					break;
				}
			}

			//Insert if not found
			if(i >= heap.size()) {
				insert(newNode);
				return;
			}

			if(newNode.f > heap[i].f) {
				heap[i] = newNode;
				siftUp(i);
			}
		}
示例#13
0
void* BinaryHeap_extract_item(BinaryHeap h, int id){
  /* extract an item with ID out and delete it */
  void *item;
  int *id_to_pos = h->id_to_pos;
  int pos;

  if (id >= h->max_len) return NULL;

  pos = id_to_pos[id];

  if (pos < 0) return NULL;

  assert(pos < h->len);

  item = (h->heap)[pos];

  IntStack_push(h->id_stack, id);

  if (pos < h->len - 1){/* move the last item to occupy the position of extracted item */
    swap(h, pos, h->len - 1);
    (h->len)--;
    pos = siftUp(h, pos);
    pos = siftDown(h, pos);
  } else {
    (h->len)--;
  }
 
  (h->id_to_pos)[id] = -1;

  return item;

}
示例#14
0
文件: Heap.c 项目: DeanWay/Heap
/* FIXME:
 * This operation is Dangerous. If the backing array does not
 * have enough space allocated to support the new node, 
 * a segmenation fault will occur
 */
Heap * insertNode(Heap *heap, void *node){
    heap->length += 1;
    heap->array[heap->length - 1] = node;

    siftUp(heap, heap->length - 1);
    
    return heap;
}
示例#15
0
文件: fringe.c 项目: dududcbier/AI
void siftUp(State *s, int n, int i){
  int child = i;
  int parent = i / 2;

  if (child > 1 && s[child].cost < s[parent].cost) {
    swap(s, parent, child);
    siftUp(s, n, parent);
  }
}
示例#16
0
void changePriority (queue *q, int ind, double newPriority)
{
	int oldPriority = q->root[q->index[ind]].priority;
	q->root[q->index[ind]].priority = newPriority;
	if (oldPriority < newPriority)
		siftDown (q, q->index[ind]);
	else if (oldPriority > newPriority)
		siftUp (q, q->index[ind]);
}
示例#17
0
	void siftUp(unsigned int index) {
		if(index <= 1) return;

		unsigned int parent_index = parent(index);
		if(Ops::pred(heap[index], heap[parent_index])) {
			swap(index, parent_index);
			siftUp(parent_index);
		}
	}
示例#18
0
int InsertHeap(pHeapHeader pHH, ElemType value)
{
	if(pHH->currentSize >= MaxHeapSize) {
		printf("没有足够堆空间!\n");
		return 0;
	}
	(pHH->point)[pHH->currentSize] = value;
	siftUp(pHH, pHH->currentSize);
	(pHH->currentSize)++;
	return 1;
}
示例#19
0
文件: Heap.c 项目: DeanWay/Heap
void siftUp(Heap *heap, int node){
    if(NULL==heap){
        return;
    }
    if (node > 0){
        if(heap->compare(heap->array[node], heap->array[parent(node)])==-1){
            void *temp=heap->array[node];
            heap->array[node]=heap->array[parent(node)];
            heap->array[parent(node)]=temp;
            siftUp(heap, parent(node));
        }
    }
}
示例#20
0
/*
* Big O: O(logn)
* Helper function. Helps the insert function insert an element into the heap and maintain the heap structure
* Moves the element up through the heap to the proper location
*/
void siftUp(int index)
{
    if(index != 0)//if the element is not at the top of the heap
    {
        int parentIndex = PARENT(index);//Figure out what is the parent of the element you are trying to fix
        if (getData(heap[parentIndex]) > getData(heap[index]))//if the parent is greater than the node you are trying to fix
        {
            struct tree  *tmp = heap[parentIndex]; //Save the value of the parent
            heap[parentIndex] = heap[index];//Move the node you are trying to fix as its parent
            heap[index] = tmp;//Move the parent to the index of the node you are trying to fix
            siftUp(parentIndex);//Sift up the node to ensure heap structure is preserved
        }
    }
}
示例#21
0
    void remove(size_t index)
    {
        require(index < heap_.size(), "Index is out of range");

        swap(heap_[index], heap_.back());

        HeapElement* result = heap_.back();
        heap_.pop_back();

        siftDown(index);
        if (index < heap_.size()) {
            siftUp(index);
        }
    }
示例#22
0
	void remove(const T* data) {
		unsigned int index = Ops::getHeapIndex(data);
		swap(index,fill);
		fill--;
		if(index <= fill) {
			int parent_index = parent(index);
			if(index > 1 && Ops::pred(heap[index], heap[parent_index])) {
				siftUp(index);
			}
			else {
				siftDown(index);
			}
		}
	}
示例#23
0
static int siftUp(BinaryHeap h, int nodePos){
  int parentPos;

  void **heap = h->heap;


  if (nodePos != 0) {
    parentPos = ParentPos(nodePos);

    if ((h->cmp)(heap[parentPos], heap[nodePos]) == 1) {/* if smaller than parent, swap */
      swap(h, parentPos, nodePos);
      nodePos = siftUp(h, parentPos);
    }
  }
  return nodePos;
}
示例#24
0
	void createFromVector(std::vector<T*>& vec) {
		if(heap.size() < vec.size()) {
			unsigned int size = heap.size() * 2;
			while(size < vec.size()) {
				size *= 2;
			}
			heap.resize(size);
		}
		fill = 0;
		for(auto item = vec.begin(); item != vec.end(); ++item) {
			heap[1 + fill++] = *item;
		}
		for(int i = fill / 2; i > 0; i--) {
			siftUp(i);
		}
	}
示例#25
0
int BinaryHeap_reset(BinaryHeap h, int id, void *item){
  /* reset value of an item with specified id */
  int pos;

  if (id >= h->max_len) return -1;
  pos = h->id_to_pos[id];
  if (pos < 0) return -1;

  h->heap[pos] = item;

  pos = siftUp(h, pos);

  pos = siftDown(h, pos);

  return pos;

}
void huffman(void)
{ struct CForest min1, min2;
  while (treeCnt > 1) {
    /* Намиране и премахване на двата най-леки върха */
    min1 = forest[1];
    removeMin();
    min2 = forest[1];
    removeMin();
    /* Създаване на нов възел - обединение на двата най-редки */
    forest[++treeCnt].root = (struct tree *) malloc(sizeof(struct tree));
    forest[treeCnt].root->left = min1.root;
    forest[treeCnt].root->right = min2.root;
    forest[treeCnt].weight = min1.weight + min2.weight;
    /* Вмъкване на възела */
    siftUp(treeCnt);
  }
}
示例#27
0
void D_HEAP<KeyType>::deleteElem(int idx) {
    if ((idx >= sizeTree_) || (idx < 0))
        throw myExcp("Out of range.");

    swap(idx, sizeTree_ - 1);

    sizeTree_--;

    if (tree_[idx] < tree_[getParentIndex(idx)]) {
        cout << 2 << endl;

        siftUp(idx);
    }
    else {

        siftDown(idx);
    }
}
示例#28
0
static void siftUp (pqueue_t *q, int i)
{
	if (0 == i)
		return;

	int p = (i - 1) / 2;

	if (q->root[p].priority < q->root[i].priority)
		return;

	q->index[q->root[i].value] = p;
	q->index[q->root[p].value] = i;

	item swap = q->root[i];
	q->root[i] = q->root[p];
	q->root[p] = swap;

	return siftUp (q, p);
}
示例#29
0
	void siftFromItem(const T *data, bool debug = false) {

		unsigned int index = Ops::getHeapIndex(data);
		if(index > 0 && index <= fill) {
			int parent_index = parent(index);
			if(index > 1 && Ops::pred(heap[index], heap[parent_index])) {
				if(debug) { fprintf(stderr, "up\n"); }
				siftUp(index);
			}
			else {
				if(debug) { fprintf(stderr, "down\n"); }
				siftDown(index, debug);
			}
		}

		// if(!checkInvariant()) {
		// 	fprintf(stderr, "invariant failed going out of siftFromItem\n");
		// 	exit(1);
		// }
	}
示例#30
0
文件: fringe.c 项目: dududcbier/AI
Fringe insertFringe(Fringe fringe, State s, ...) {
  /* Inserts s in the fringe, and returns the new fringe.
   * This function needs a third parameter in PRIO(HEAP) mode.
   */
  int priority;
  va_list argument;

  if (fringe.size == MAXF) {
    fprintf(stderr, "insertFringe(..): fatal error, out of memory.\n");
    exit(EXIT_FAILURE);    
  }
  fringe.insertCnt++;
  switch (fringe.mode) {
  case LIFO: /* LIFO == STACK */
  case STACK:
    fringe.states[fringe.size] = s;
    break;
  case FIFO:
    fringe.states[fringe.rear++] = s;
    fringe.rear %= MAXF;
    break;
  case PRIO: /* PRIO == HEAP */
  case HEAP:
    /* Get the priority from the 3rd argument of this function.
     * You are not supposed to understand the following 5 code lines.
     */
    va_start(argument, s); 
    priority = va_arg(argument, int);
    // printf("priority = %d ", priority);
    va_end(argument);
    s.cost = priority;
    fringe.states[fringe.size + 1] = s;
    siftUp(fringe.states, fringe.size + 1, fringe.size + 1);
    break;
  }
  fringe.size++;
  if (fringe.size > fringe.maxSize) {
    fringe.maxSize = fringe.size;
  }
  return fringe;
}