Can someone point out what possible edge cases/leaks/inefficiencies my code has and how they could be avoided/fixed. Basically, I want to know what mistakes I make so I can avoid making them in the future.
I chose an LSD radix sort function as a sample for no particular reason.
The function:
//arrPtr - pointer to the array being sorted; count - its count
//scoreFunction - function that assigns scores to elements based on which they will be sorted in ascending order
//args - pointer to an array of pointers used to pass data to the scoreFunction
template<class T>
void rsort(T *arrPtr, size_t count, int scoreFunction(T val, void **args) = [](T val, void **args) {return val; }, void **args = nullptr) {
struct elem { //Pairing indices with their scores
size_t idx;
int scr;
};
struct elemPtr { //Pointer struct to avoid memory leaks in case of an exception
elem *ptr;
~elemPtr() { delete[] ptr; }
void swap(elemPtr &aux) {
elemPtr t{ ptr };
ptr = aux.ptr;
aux.ptr = t.ptr;
t.ptr = nullptr;
}
};
elemPtr srt{ new elem[count] }, srtAux{ new elem[count] };
for (size_t i = 0; i < count; ++i) { //Assigning indices and scores that are converted to unsigned representation + 2^31
srt.ptr[i].idx = i;
srt.ptr[i].scr = scoreFunction(arrPtr[i], args) ^ 0x80000000;
}
for (unsigned char bShft = 0; bShft < 32; bShft += 8) { // Base 256 LSD radix sort based on the scores
size_t dCnt[256]{};
for (size_t i = 0; i < count; ++i)
++dCnt[srt.ptr[i].scr >> bShft & 255];
for (unsigned char i = 0; i < 255; ++i)
dCnt[i + 1] += dCnt[i];
for (size_t i = count; i > 0; --i) {
--dCnt[srt.ptr[i - 1].scr >> bShft & 255];
srtAux.ptr[dCnt[srt.ptr[i - 1].scr >> bShft & 255]] = srt.ptr[i - 1];
}
srt.swap(srtAux);
}
for (size_t i = 0; i < count; ++i) //Filling with 0s to reuse as an array of bools that represent if the element is in the right place
srtAux.ptr[i].idx = 0;
for (size_t i = 0; i < count; ++i) { //Rearranging the original array by dividing the elements into enclosed loops
if (srtAux.ptr[i].idx)
continue;
T temp = arrPtr[i];
size_t curIdx = i;
while (srt.ptr[curIdx].idx != i) {
srtAux.ptr[curIdx].idx = 1;
arrPtr[curIdx] = arrPtr[srt.ptr[curIdx].idx];
curIdx = srt.ptr[curIdx].idx;
}
srtAux.ptr[curIdx].idx = 1;
arrPtr[curIdx] = temp;
}
}
I didn't use any libraries to make the function independent-- if that makes sense.