Skip to content

Instantly share code, notes, and snippets.

@gsdayton98
Last active August 29, 2015 14:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsdayton98/bc97e20a482f112a4a2b to your computer and use it in GitHub Desktop.
Save gsdayton98/bc97e20a482f112a4a2b to your computer and use it in GitHub Desktop.
C++ code to delete duplicates from an array using a heap structure to achieve O(n*log n) performance
#include <cstdlib>
#include <algorithm>
// Delete duplicate entries from an array using C++ heap.
int *deleteDuplicates(int theArray[], size_t theArrayLength)
{
int *topSortedArray = theArray + theArrayLength;
if (theArrayLength > 1)
{
// Heap is in theArray[0:heapEnd-1]
size_t heapEnd = theArrayLength;
std::make_heap(theArray, theArray+heapEnd);
// Pop the first element, which is the max element
int prevElement = theArray[0];
std::pop_heap(theArray, theArray+heapEnd);
--heapEnd;
// push the max element onto the sorted area
--topSortedArray;
*topSortedArray = prevElement;
while (heapEnd > 0)
{
int currentElement = theArray[0];
std::pop_heap(theArray, theArray+heapEnd);
--heapEnd;
if (currentElement != prevElement)
{
--topSortedArray;
*topSortedArray = currentElement;
prevElement = currentElement;
}
}
}
return topSortedArray;
}
@gsdayton98
Copy link
Author

Delete duplicate entries in an array using C++ heap

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment