An even quicker look at insertion sort.

While I was on the ye old college try I went ahead and ripped the guts of bubble sort and inserted insertion sort. It is very similar to bubble sort:

/*
Author: Anthony Wlodarski
Created On: 1/18/10
Insertion Sort Function
*/

// Pre: valid array
// Post: returns an array sorted with the bubble sort algorithm
function insertion_sort($values = array())
{
if(count($values) < 2)
{
return $values;
}

// we have an array with at least two items to sort
$total_number_of_values = count($values);

// for each element we must loop through the loop
for($j = 1; $j < $total_number_of_values; $j++)
{
$i = $j-1;
$temp = $values[$j];
while(($i >= 0) && ($temp < $values[$i]))
{
$values[$i+1] = $values[$i];
$i--;
}
$values[$i+1] = $temp;
}

return $values;
}

$elements = array();
$total_elements = rand(0, 50);
for($a = 0; $a < $total_elements; $a++)
{
$elements[$a] = rand(0, PHP_INT_MAX);
}


$sorted_elements =insertion_sort($elements);

0 Responses to An even quicker look at insertion sort.

  1. There are currently no comments.

Leave a Reply



About

User