According to my knowledge quicksort is one of the fastest sorting algorithms, since thats how the Array.Sort() function is implemented in the framework. Is there a way to speed the sorting of a byte array up, probably using unsafe code and pointers?
Asked
Active
Viewed 603 times
1 Answers
2
For byte array you may consider Counting sort, which sort in linear time.
public static void Sort(byte[] a)
{
int[] counts = new int[256];
for (int i = 0; i < a.Length; i++)
counts[a[i]]++;
int k = 0;
for (int i = 0; i < counts.Length; i++)
for (int j = 0; j < counts[i]; j++)
a[k++] = (byte)i;
}

AlexD
- 32,156
- 3
- 71
- 65
-
Your code seems to have a boundary issue. I get this exception when trying your implementation: http://i.imgur.com/vzofi5W.png – yq8 Aug 28 '16 at 23:04
-
This one works, thanks. Can you explain why the creation of a 256-element big int[] is needed? And are there any other tweaks possible, - probably using pointers? :) – yq8 Aug 28 '16 at 23:08
-
"probably using pointers" --- using unsafe code does not automagically make anything better. You're trying to optimise something that you cannot measure reliably, it makes very little sense from the performance optimisation point of view. – zerkms Aug 28 '16 at 23:10
-
The counting sort utilizes the fact that there are only limited number of possible values in the array (256 in our case). During the first pass, we just count how many zeros, how many ones, how many twos etc. we have, During the second pass we place corresponding numbers or zeroes, ones, twos, etc. – AlexD Aug 28 '16 at 23:11