Exemple #1
0
  void insert(T data){
    if(MaxHeap->size()==0){
      MaxHeap->Insert(data);
      return;
    }

    T maxHeap = MaxHeap->pop();
    T minHeap = MinHeap->pop();

    if(data < maxHeap){
      MaxHeap->Delete();
      MaxHeap->Insert(data);
      swap( maxHeap, data);
    }

    if(MinHeap->size()==0){
      MinHeap->Insert(data);
      return;
    }

    if(data > minHeap){
      MinHeap->Delete();
      MinHeap->Insert(data);
      swap(data,minHeap);
    }

    if(MaxHeap->size() > MinHeap->size())
      MinHeap->Insert(data);
    else
      MaxHeap->Insert(data);
  }
/* the char* filename is just for printing the name, the file is opened and dealt with in the main() */
void heapsort(vector<int> &sortingvector, int number_of_elements, char* filename){
	/* Heap myHeap; .//declare a Heap instance here */
	Heap myHeap;
	
	/* Using the sortingvector, INSERT elements into the Heap */
	for(unsigned int i = 0; i < sortingvector.size(); ++i)
		myHeap.InsertHeap(sortingvector[i]);
	
	/* After building the heap from the file, PRINT the current state of the heap before sorting */
	cout << "Heap before sorting: " << filename << endl;
	myHeap.PrintHeap();
	
	/* STORE how many comparisons were made until this point */
	int insertComparisons = myHeap.GetComparisons();
	myHeap.ResetComparisons();
	
	/* DELETE elements from the Heap, copying it back to the vector in a way that it is sorted */
	for(unsigned int i = 0; i < sortingvector.size(); ++i) {
		int temp = myHeap.Delete();
		if(temp > 0) sortingvector[i] = temp;
	}
	
	/* STORE how many comparisons were made for the deletion process */
	int deleteComparisons = myHeap.GetComparisons();
	
	/* PRINT the number of comparisons for the Insert and Deletion tasks */
	cout << "InsertHeap: " << insertComparisons << " comparisons" << endl;
	cout << "DeleteRoot: " << deleteComparisons << " comparisons" << endl;
	
	/* Print the state of the vector after sorting */
	cout << "Vector after sorting:" << endl;
	for(unsigned int i = sortingvector.size() - 1; i > 0; --i)
		cout << sortingvector[i] << ' ';
		cout << sortingvector[0] << ' ';
	cout << endl;
}