Пример #1
0
void DebugHeapTable::build_heap(T_IDX cur_idx) {
    T_IDX lson_idx = cur_idx * 2 + 1;
    T_IDX rson_idx = cur_idx * 2 + 2;
    T_IDX last_idx = key_heap_.size() - 1;

    if (cur_idx > last_idx) {
        return;
    }

    build_heap(lson_idx);
    build_heap(rson_idx);

    down_adjust_heap(cur_idx);
}
Пример #2
0
void init_kheap()
{
	kernel_heap = build_heap((uintptr_t*)HEAP_BEGIN, 1, 0);
	
	// Self-test
	puts("heap self-test\n");
	uint32_t *test_alloc = (uint32_t*)kalloc(sizeof(uint32_t));
	uint32_t *test_alloc_2 = (uint32_t*)kalloc(sizeof(uint32_t));
	
	puts("var1(uint32_t)=");
	puthex((uintptr_t)test_alloc);
	puts(", var2(uint32_t)=");
	puthex((uintptr_t)test_alloc_2);
	puts("\n");
	
	*test_alloc = 0x1234ABCD;
	*test_alloc_2 = 0xCAFEBEEF;
	
	kfree((uintptr_t*)test_alloc);
	kfree((uintptr_t*)test_alloc_2);
	
	uint32_t* test_alloc_3 = (uint32_t*)kalloc(sizeof(uint64_t));
	puts("var1 and var2 freed, var3(uint64_t)=");
	puthex((uintptr_t)test_alloc_3);
	puts(", should be ");
	puthex((uintptr_t)test_alloc);
	puts("\n");
	
	if(test_alloc_3 == test_alloc)
		puts("self-test succeeded\n");
	
	kfree((uintptr_t*)test_alloc_3);
}
Пример #3
0
/*!
    compute the huffman code
    given a set of nonzero frequencies this procedure computes
    the code of each symbol. 
    /param freq[] frequency of each symbol (size n)
    /param n: number of symbols
    /param code_len[] code length of each symbol (size n, to be computed) 
    /param code_value[] numerical value of each symbol (size n, to be computed)
*/
void compute_huffman_code(int *freq, int n, int *code_len, int *code_value)
{
  int i, *heap;

  // start by checking that all symbols have freq!=0
  for(i=0;i<n;i++)
    assert(freq[i]>=0);

  if(n>2) {
    heap = (int *) malloc((2*n+1)*sizeof(int));
    if(heap==NULL) _huff_out_of_mem("compute_huffman_code");
    build_heap(heap,freq, n);             // build huffman heap
    build_huffman_tree(heap, n);          // build tree using the huffman heap
    compute_code_len(code_len, heap, n);  // compute code length of each symbol
    compute_code_values(code_value,code_len,n);
    free(heap);     
  }
  else if(n==2) {
    code_len[0]=code_len[1]=1;
    code_value[0]=0; code_value[1]=1;
  }
  else if(n==1)
    code_len[0]=code_value[0]=0;
  else
    _huff_fatal_error("Illegal number of symbols! (compute_huffman_code)");
}
Пример #4
0
TEST(Heap, BuildHeap_1) {
	size_t size = 3;
	int actual[] = { 1, 6, 0 };
	int expected[] = { 6, 1, 0 };
	build_heap(actual, actual + size, _INT, intComporator);
	EXPECT_ARRAY(expected, actual, _INT, size);
}
Пример #5
0
void dijkstra_heap(int** W, int s, int n){
	P = (int *)malloc(n*sizeof(int));
	D = (int *)malloc(n*sizeof(int));
	int i = 0;
	for(; i < n; i++)D[i] = INFTY;
	D[s] = 0;
	P[s] = s;
	int v = 0;
	for(; v < n; v++){
		if(W[s][v] < INFTY){
			D[v] = W[s][v];
			P[v] = s;
		}
	}
	build_heap(n,s);
	int u;
	while(hsize != 0){ 	// the heap is not empty
		u = extract_min();
		for(v = 0; v < n; v++){
			if(D[v] > D[u] + W[u][v]){
				D[v] = D[u] + W[u][v];
				P[v] = u;
				decrease_key(v,D[v]);
			}

		}
	}
}
Пример #6
0
TEST(Heap, BuildHeap_3) {
	int size = 10;
	int actual[] = { 1, 6, 0, 2, 7, 9, 4, 8, 3, 5 };
	int expected[] = { 9, 8, 4, 6, 7, 0, 1, 2, 3, 5 };
	build_heap(actual, actual + size, _INT, intComporator);
	EXPECT_ARRAY(expected, actual, _INT, size);
}
Пример #7
0
TEST(Heap, BuildHeap_2) {
	int size = 5;
	int actual[] = { 1, 6, 0, 2, 7 };
	int expected[] = { 7, 6, 0, 2, 1 };
	build_heap(actual, actual + size, _INT, intComporator);
	EXPECT_ARRAY(expected, actual, _INT, size);
}
Пример #8
0
int main() {
	int *a;
	int n,i;	
	printf ("Enter the size of heap: ");
	scanf (" %d", &n);
	a = malloc (n*sizeof(int));
	printf ("Enter %d elements: ", n);

	for (i=0; i<n; i++) {
        scanf (" %d", &a[i]);
    }

	build_heap(a,n);
	printf ("After build_heap: ");
	for (i=0; i<n; i++)
        printf ("%d ", a[i]);
	
	printf ("\nMax: %d\n", extract_max(a,&n));
	printf ("Max: %d\n", extract_max(a,&n));
	printf ("Max: %d\n", extract_max(a,&n));
	printf ("Max: %d\n", extract_max(a,&n));

	// Heap after extract_max
	for (i=0; i<n; i++)
        printf ("%d ", a[i]);
	printf ("\n");
	free(a);
	return 0;
}
Пример #9
0
/**
 *  Builds a Huffman tree using the collected character frequencies.
 */
    PUBLIC node_t *
build_huffman_tree (void)
{
    node_t *array [ALPHABET_LENGTH + 2];
    node_t *parent, *child1, *child2;
    heap_t heap;

    heap.array = array;
    heap.num_items = 0;
    heap.num_free_slots = ALPHABET_LENGTH + 2;

    build_heap (&heap);

    while (heap.num_items > 1)
    {
        child1 = heap_dequeue (&heap);
        child2 = heap_dequeue (&heap);

        parent = new_node (size (child1) + size (child2), child1, child2);

        heap_enqueue (&heap, parent);
    }

    return heap_dequeue (&heap);
}
Пример #10
0
int main()
{
	int i, temp, j;
	
	printf("Before Heap\n");	
	for (i=0; i<MAXVAL; i++)
		printf("%d ", a[i]);
	printf("\n");

	build_heap(n);
	for (i=n ; i>0 ; i--) {
		// swapping the max value to the last 
		// element of the array
		temp = a[0];
		a[0] = a[i]; 
		a[i] = temp;
	
		n--;
		heapify(0, n);
	}
	

	printf("After Heap\n");	
	for (i=0; i<MAXVAL; i++)
		printf("%d ", a[i]);
	printf("\n");
	return 0;
}
Пример #11
0
void
init(char *str, int len)
{
	int i;
	char *lp = str;
	struct Node *node;
	heap_size = 0;
	memset(count, 0, sizeof(count));
	while(*lp) {
		++count[(*lp)-'a'];
		++lp;
	}

	for(i=0; i<LEN; i++) {
		if(count[i]) {
			node = (struct Node *)malloc(sizeof(struct Node));
			node->c = i+'a';
			node->weight = count[i];
			node->left = node->right = NULL;
			heap_array[heap_size++] = node;
		}
	}
	num = heap_size; /* total number of characters */
	build_heap();
}
void Dijkstra(Grafo G, vertice* vertice_origem, int num_vertices){
	int i = 0, j = 0, tam_heap = 0, posicao_vizinho = 0;
	vertice *prox_fila;
	vertice** heap;
	// Inicializa o peso de todos os vértices até a origem com "infinito".
	for(i = 1; i <= num_vertices; i++){
		G[i]->peso_origem = 2147483646; /* Valor máximo possível para um inteiro. (Representa "infinito") */
		G[i]->antecessor = NULL;
	}
	vertice_origem->peso_origem = 0;
	heap = (vertice**) malloc((num_vertices+1)*sizeof(vertice*));
	// Formar um vetor com o peso acumulado(desde a orgiem) de todos os vértices.
	for(i = 1; i <= num_vertices; i++)
		heap[i] = G[i];
	tam_heap = num_vertices;
	// Construir um heap, que deixará o o vértice com o menor peso na frente.
	build_heap(heap, tam_heap);
	j = 1;
	while(tam_heap > 0){
		// Verifica o vértice com o menor peso.
		prox_fila = heap[j];
		// Marca o vértice com uma flag, para indicar que o peso final do seu caminho mínimo já foi determinado.
		prox_fila->flag = 1;
		// Retira o vértice do heap.
		tam_heap--;
		// Verificar o peso da aresta para cada um dos vértices vizinhos.
		vertice* proximo_vizinho;
		proximo_vizinho = prox_fila->prox;
		if(proximo_vizinho != NULL)
			posicao_vizinho = proximo_vizinho->campo;
		if(prox_fila->peso_origem == 2147483646)
			break;
		for(i = 0; i < prox_fila->num_vizinhos; i++){
			// Se o peso final do do caminho até o vértice ainda não foi determinado, verifica se o peso do caminho mínimo pode ser "relaxado".
			if(G[posicao_vizinho]->flag != 1)
				Relax(G, prox_fila, G[posicao_vizinho]);
			// Verifica qual vértice é o próximo vizinho a ser analisado.
			proximo_vizinho = proximo_vizinho->prox;
			if(proximo_vizinho != NULL)
				posicao_vizinho = proximo_vizinho->campo;
		}
		// Reconstrói o heap.
		build_heap(&(heap[j]), tam_heap);
		j++;
	}
	free(heap);
}
Пример #13
0
void heap_sort(Array array, int n) {
  build_heap(array, n);
  int i;
  for (i = n - 1; i > 0; --i) {
    swap(array, 0, i);
    heapify(array, 0, i);
  }
}
Пример #14
0
void heap_sort(int *list,int *dest, int length)
{
    build_heap(list,dest,length);
    for (int i = length - 1; i > 0; --i) {
        interchange(dest,0,i);
        heapify(dest,i);
    }
}
Пример #15
0
inline void heap_sort(Iter first, Iter last)
{
    build_heap(first, last);
    for (auto curr = last - 1; curr != first; --curr)
    {
        std::swap(*first, *curr);
        heapify(first, curr, first);
    }
}
Пример #16
0
void
heap_sort(data_t A[], int n) {
	int active;
	build_heap(A, n);
	for (active=n-1; active>0; active--) {
		swap_data(A+0, A+active);
		sift_down(A, 0, active);
	}
}
Пример #17
0
Файл: WDG.c Проект: mdilshad/DSA
struct vertex * extract_min(struct vertex **Q)
{
	int i;
	build_heap(Q,n);
	struct vertex *min;
		min=Q[0];
		Q[0]=Q[n-1];
		n--;
		return min;
}
Пример #18
0
void heap_sort(vector<int> &array, int size)
{
    int i;
    build_heap(array, size);
    for (i = size; i >= 1; i--) {
        swap(array[1], array[i]);
        heap_adjust(array, 1, i - 1);
        print_sort(array);
    }
}
void heap_sort(int a[], int n) //пирамидальна¤ сортировка
{
	build_heap(a, n);
	for (int i = 0; i < n - 1; i++) 
	{
		int t = a[n - 1 - i];
		a[n - 1 - i] = a[0];
		a[0] = t;
		heapify(a, n - 1 - i, 0);
	}
}
Пример #20
0
void heap_sort(int a[], int n) {
	//TODO: write your heap sort
	build_heap(a, n);//куча построена
	int heap_size = n - 1;
	for (int i = n - 1; i > 0; i--)
	{
		swap(a[0], a[i]);
		heap_size = heap_size - 1;// уменьшаем на 1, тк последний элемент кучи уже отсортирован
		heapify(a, 0, heap_size);//в построенной куче поддерживаем её основное свойство
	}
}
void heap_sort(int* array, int n) {
  int heap_size = n;
  build_heap(array, n);
  for (int i=n-1; i>0; i--) {
    int t = array[i];
    array[i] = array[0];
    array[0] = t;
    heap_size--;
    max_heapify(array, 0, heap_size);
  }
}
int main(){
  
  int i;
  int a[MAX] = {1, 17, 3, 16, 13, 10, 1, 5, 7, 12, 4, 8, 9, 0};
  build_heap(a);
  heap_sort(a);
  while(i < MAX){
    printf(" %d ", a[i]);
    i++;
  }
  printf("\n");
}
Пример #23
0
Файл: def.c Проект: mdilshad/DSA
void heap_sort(int *A,int n)
{
    int size,temp;
    build_heap(A,n);
    for(size=n-1; size>0; size--)
    {
        temp=A[0];
        A[0]=A[size];
        A[size]=temp;
        heapify(A,1,size);
    }
}
Пример #24
0
// Assume the array is initialized
heap *initializeHeap(int *array, int size){
	if(array != NULL && size > 0){
		heap *h = (heap *)malloc(sizeof(heap));
		h->heap = array;
		h->size = size;
		build_heap(h);

		return h;
	}else{
		return NULL;
	}
}
Пример #25
0
/* 堆排序 */
void hsort(int *array, int len, fun compare)
{
    int index = len - 1;
    
    build_heap(array, len, compare);

    for(; index > 0; --index) {
        /* 堆顶数是堆中最大/最小的数,将其放到排序后的正确位置 */
        swap(array + 0, array + index);
        /* 重建堆 */
        heapify(array, 0, index, compare);
    }
}
Пример #26
0
/* Initialize a single-source shortest-paths computation. */
void initialize_single_source(double key[], int handle[], int heap_index[],
			      int pi[], int s, int n) {
  int i;
  for (i = 1; i <= n; ++i) {
    key[i] = 1000000000.0;
    handle[i] = i;
    heap_index[i] = i;
    pi[i] = 0;
  }

  key[s] = 0.0;
  build_heap(key, handle, heap_index, n);
}
Пример #27
0
 void head_sort(int* base, int len)
 {
     if(base == NULL || len == 0)
     {
         return;
     }
     build_heap(base,len);
     for(int i = len - 1; i >= 0; --i)
     {
         swap(base,base + i);
         heap_maxify(base,0,i);
     }
 }
Пример #28
0
void heap_sort(int h[],int size)
{
	int i;
	int temp;
	build_heap(h,size);

	for(i=size-1;i>0;i--) {
		temp=h[0];
		h[0]=h[i];
		h[i]=temp;
		max_heapify(h,i,0);
	}

}
Пример #29
0
int main(int argc, char ** argv)
{
	  int i;
	  print_array();
	  build_heap();
	  print_array();
	  insert(22);
	  print_array();
	  print_rec(1, 0);
	  for (i=1; i<=SIZE; ++i) 
		printf(" %d , ", max_del());
	  printf("\n");
	  return 0;
}
Пример #30
0
void heap_sort (void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *))
{
  int h_size = nmemb, i;
  
  build_heap (base, &h_size, size, compar);
  for (i=nmemb-1; i>=0; i--)
  {
    block_swap (base + 0 * size, base + i * size, size);
    h_size--;
    heapify (base, &h_size, 0, size, compar);
  }

  return;
}