diff --git a/thiersort.h b/thiersort.h index f7207ff..1e9b827 100644 --- a/thiersort.h +++ b/thiersort.h @@ -426,23 +426,25 @@ static inline void thiersort_apply( /* Replace the whole chain starting at i (j for chain index) */ /* This works because we can easily check what does'nt need moves anymore. */ TSU32 j = i; - TSU32 ni = sortres[j].i; + TSU32 ni = sortres[j].i; /* (*) */ /* Until would move to its own position, chain */ /* This also solves "already at right place" originals. */ while(ni != j) { - /* xchg j and ni */ - memcpy(tmp, &((TSU8*)arr)[(size_t)j * elemsize], elemsize); - memcpy( - &((TSU8*)arr)[(size_t)j * elemsize], - &((TSU8*)arr)[(size_t)ni * elemsize], - elemsize); - memcpy(&((TSU8*)arr)[(size_t)ni * elemsize], tmp, elemsize); + /* xchg j and ni - but only if not already swapped! See: (*) */ + if(sortres[ni].i != ni) { + memcpy(tmp, &((TSU8*)arr)[(size_t)j * elemsize], elemsize); + memcpy( + &((TSU8*)arr)[(size_t)j * elemsize], + &((TSU8*)arr)[(size_t)ni * elemsize], + elemsize); + memcpy(&((TSU8*)arr)[(size_t)ni * elemsize], tmp, elemsize); + } /* Mark j index as done in sortres for outer loop. */ /* This is necessary for inner loop stopping early */ /* and outer catch up on already processed location. */ - sortres[j].i = j; + sortres[j].i = j; /* (*) */ /* Update j and ni */ /* Now we must find what should be at new location j */ @@ -451,6 +453,9 @@ static inline void thiersort_apply( ni = sortres[j].i; } } + + /* Release mem - better we do because we changed it behind the scenes! */ + free(sortres); } /**