Exemple #1
0
// The main function that builds Huffman tree
struct node* buildHuffmanTree(char data[], int freq[], int size)
{
    struct node *left, *right, *top;
 
    // Step 1: Create a min heap of Limit equal to size.  Initially, there are
    // modes equal to size.
    struct Heap* Heap = createAndBuildHeap(data, freq, size);
 
    // Iterate while size of heap doesn't become 1
    while (!isSizeOne(Heap))
    {
        // Step 2: Extract the two minimum freq items from min heap
        left = extractMin(Heap);
        right = extractMin(Heap);
 
        // Step 3:  Create a new internal node with frequency equal to the
        // sum of the two nodes frequencies. Make the two extracted node as
        // left and right children of this new node. Add this node to the min heap
        // '$' is a special value for internal nodes, not used
        top = newNode('$', left->freq + right->freq);
        top->left = left;
        top->right = right;
        insertHeap(Heap, top);
    }
 
    // Step 4: The remaining node is the root node and the tree is complete.
    return extractMin(Heap);
}
Exemple #2
0
void heapSort(int *array, int size)
{
    struct MaxHeap *maxHeap = createAndBuildHeap(array, size);
    
    while(maxHeap->size > 1)
    {
        swap(&maxHeap->array[0], &maxHeap->array[maxHeap->size -1]);
        --maxHeap->size;
    
        maxHeapify(maxHeap, 0);
    }
}
Exemple #3
0
void heapSort(int *arr, int size)
{
	struct heap *maxHeap = createAndBuildHeap(arr, size);

	while(maxHeap->size > 1)
	{
		int temp = maxHeap->arr[0];
		maxHeap->arr[0] = maxHeap->arr[maxHeap->size - 1];
		maxHeap->arr[maxHeap->size - 1] = temp;

		--maxHeap->size;

		buildMaxHeap(maxHeap, 0);
	}
}
Exemple #4
0
// The main function to sort an array of given size
void heapSort(int* array, int size)
{
  // Build a heap from the input data.
  struct MaxHeap* maxHeap = createAndBuildHeap(array, size);
  
  // Repeat following steps while heap size is greater than 1.
  // The last element in max heap will be the minimum element
  while (maxHeap->size > 1) {
    // The largest item in Heap is stored at the root. Replace
    // it with the last item of the heap followed by reducing the
    // size of heap by 1.
    swap(&maxHeap->array[0], &maxHeap->array[maxHeap->size - 1]);
    --maxHeap->size;  // Reduce heap size
    
    // Finally, heapify the root of tree.
    maxHeapify(maxHeap, 0);
  }
}