Implement Insertion Sort in PHP

Steps:

  1. Start Iterate from data_array[1] to data_array[n].
  2. Compare the current element to its predecessor.
  3. If the current element is smaller than its predecessor, then move the predecessor elements to current elements key until the current element is greater then predecessor element and place the current element to it’s appropriate position.
$data_array = [1,3,44,22,38,5,47,15,36,26,27,12];

function insertion_sort( $data_array ){
	for( $i=1; $i < count( $data_array ); $i++ ){
		$item = $data_array[$i];
		$j = $i - 1;
		while( $j >= 0 && $data_array[$j] > $item ){
			$data_array[$j+1] = $data_array[$j];
			$j--;
		}
		$data_array[$j + 1] = $item;
	}
	return $data_array;
}

echo '<h1>Before Sort</h1>';
echo '<pre>';
print_r($data_array);
echo '</pre>';
echo "<br>";
echo '<h1>After Sort</h1>';
$sorted_items = insertion_sort( $data_array ); 
echo '<pre>';
print_r($sorted_items);
echo '</pre>';

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *