
$arr = array(10,5,2,88,33,5,2,7,23,99,3,1);
function bubbleSort($arr) {
for($j = 0; $j < count($arr); $j++) {
for($i = 0; $i < count($arr)-1; $i++){
if($arr[$i] > $arr[$i+1]) { // 10 > 5
$temp = $arr[$i+1]; // temp = 5
$arr[$i+1]=$arr[$i]; // array[1] = 10
$arr[$i]=$temp; // arr[0] = temp
}
}
}
return $arr;
}
echo 'Bubble Sort --';
print_r(bubbleSort($arr));
function selectionSort(array $arr)
{
$n = sizeof($arr);
for ($i = 0; $i < $n; $i++) {
$lowestValueIndex = $i;
$lowestValue = $arr[$i];
for ($j = $i + 1; $j < $n; $j++) {
if ($arr[$j] < $lowestValue) {
$lowestValueIndex = $j;
$lowestValue = $arr[$j];
}
}
$arr[$lowestValueIndex] = $arr[$i];
$arr[$i] = $lowestValue;
}
return $arr;
}
echo 'Selection Sort --';
print_r(selectionSort($arr));
function binaryInsertionSort($arr)
{
if(!empty($arr)) {
for($i=0;$i $temp = $arr[$i];
$left = 0;
$right = 1;
while($left<$right) {
$mid = floor(($left+$right)/2);
if($temp >= $arr[$mid]) {
$left = $mid+1;
}
else {
$right = $mid;
}
}
for($j=$i;$j>$left;--$j) {
$temp1 = $arr[$j-1];
$arr[$j-1] = $arr[$j];
$arr[$j] = $temp1;
}
}
}
return $arr;
}
echo 'Binary Insertion Sort --';
print_r(binaryInsertionSort(array(56,32,43,3,4)));
Complexity :: O(n log n);
Post a Comment