The Bubble variety is slow, it compares and swaps your values up to 4096 * 4096 = 16,777,216 times. If you only need the 8 best values, choosing 1 sweep will be faster with confidence. By itself so.
const uint_t n = 8; uint_t best[n] = {0}; uint_t index[n] = {0}; uint_t j; for(uint_t i=0; i<4096; i++) { if(counter[i] > best[n-1]) { for(j=n-2; j && counter[i] > best[j]; j--); memmove(&best [j+1], &best[j] , (n-1 -j) * sizeof best[0]); memmove(&index[j+1], &index[j], (n-1 -j) * sizeof index[0]); best[j] = counter[i]; index[j] = i;
value was. * /}}
In this case, you compare your values only once, and the cost of memmove negligible, because your array of choice is small. There is no need to sort the array, this algorithm is O (n), the best type is O (n.log2 n)
EDIT : I added an array for the index. EDIT2 : the second one was introduced to fix the main error that I had in the first case. EDIT3 : Comment: memmove with size 0 is allowed and is basically nop.
source share