I've implemented InsertionSort and SelectionSort in PHP and tested it with an array of 20.000 unique integers.
It took many seconds to complete the insertion selection sorts. For comparison, I saw a Java implementation that only took 3 seconds for both combined. I wanted to ask if my implementations are just bad or if this is a hardware/language based problem.
Here are my methods:
$rand = randomArray(20000);
insertionSort($rand);
selectionSort($rand);
function insertionSort($sort_array){
$time_start = microtime(true);
for ($i = 0; $i < count($sort_array)-1; $i++){
for ($j = $i + 1; $j > 0; $j--)
{
if($sort_array[$j-1] > $sort_array[$j]){
$temp = $sort_array[$j-1];
$sort_array[$j-1] = $sort_array[$j];
$sort_array[$j] = $temp;
}
}
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo $time;
return $sort_array;
}
function selectionSort($sort_array)
{
$time_start = microtime(true);
for ($i = 0; $i < count($sort_array) - 1; $i++)
{
$min = $i;
for ($j = $i + 1; $j < count($sort_array); $j++)
{
if ($sort_array[$j] < $sort_array[$min]){
$min = $j;
}
$temp = $sort_array[$i];
$sort_array[$i] = $sort_array[$min];
$sort_array[$min] = $temp;
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo $time;
return $sort_array;
}
}
function randomArray($max){
$random = range(0, $max-1);
shuffle($random );
return $random;
}