Last active
August 29, 2015 14:26
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Delete duplicate entries in an array using C++ heap