Insertion Sort

PHP

// Function to sort an array 
// using insertion sort 
function insertionSort(&$arr, $n) 
{ 
	for ($i = 1; $i < $n; $i++) 
	{ 
		$key = $arr[$i]; 
	
		// Move elements of arr[0..i-1], 
		// that are greater than key, to 
		// one position ahead of their 
		// current position 
		for ($j = $i - 1; $j >= 0 && $arr[$j] > $key; $j--) {
	        $arr[$j + 1] = $arr[$j];
	        $arr[$j] = $key;
		} 
	} 
} 

Leave a Reply