I know how to write an algorithm that sorts a binary array in O(n)
time and O(1)
auxiliary space complexity, but it doesn't seem to be stable.
void binarySort(int arr[], int arr_size)
{
int i;
int count_zeros=0;
for (i=0 ; i<arr_size ; i++)
{
if(arr[i]==0)
count_zeros++;
}
int j;
for(j=0 ; j<count_zeros ; j++)
arr[j]=0;
int k;
for(k=j ; k<arr_size ; k++)
arr[k]=1;
}
Consider I want to perform binary radix sort using the stable sort algorithm as a subroutine. Here is an example in which we sort we sort according to the least significant bit.
Input: 11, 101, 1000, 1010, 111, 110, 10
Output: 1000, 1010, 110, 10, 11, 101, 111
Notice in the example above, the order of the binary numbers with the same LSBs is preserved.
Is there any way to edit the above algorithm or make a new algorithm such that the sort algorithm is stable while preserving it's O(n)
time complexity and O(1)
auxiliary space complexity?
From Wikipedia: Stable sorting algorithms maintain the relative order of records with equal keys (i.e. values). That is, a sorting algorithm is stable if whenever there are two records R and S with the same key and with R appearing before S in the original list, R will appear before S in the sorted list. For those who say that stability doesn't matter, read this post.