0

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?

1
  • 1
    Using lower level primitives does not improve the complexity of the algorithm. Commented Aug 28, 2016 at 22:46

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Your code seems to have a boundary issue. I get this exception when trying your implementation: i.imgur.com/vzofi5W.png
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? :)
"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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.