Could you plese help me to create an optimized php custom function for sorting a binary array ? Now, I am using the bubble sort algorithm with two for loops. My code given below :
for ( $i = 0; $i < $array_size; $i++ )
{
for ($j = 0; $j < $array_size; $j++ )
{
if ($numbers[$i] < $numbers[$j])
{
$temp = $numbers[$i];
$numbers[$i] = $numbers[$j];
$numbers[$j] = $temp;
}
}
}
Bubble sort in an
O(N^2)you can use the below approach which isO(N):Find the sum of all elements in the array. It’ll give you the number of
1‘s in the array. You can use the array_sum() function for this. Call the results. Also letnbe the number of elements in the array.The sorted array will have
n-snumber of0s followed bysnumber of1‘s.Note that you can’t do better than
O(N)as you must touch each array element once.