Skip to content

Instantly share code, notes, and snippets.

@TechZi
Created June 22, 2010 03:05
Show Gist options
  • Save TechZi/447873 to your computer and use it in GitHub Desktop.
Save TechZi/447873 to your computer and use it in GitHub Desktop.
<?php
$arr = array(77, 99, 44, 55, 22, 88, 11, 00, 66, 33);
function bubbleSort($arr) {
$length = count($arr);
for ($i = $length; $i > 1; $i--) {
for ($j = 0; $j < $i; $j++) {
if ($arr[$j] > $arr[$j + 1]) {
$tmp = $arr[$j];
$arr[$j] = $arr[$j + 1];
$arr[$j + 1] = $tmp;
}
}
}
display($arr);
}
function display($arr) {
foreach($arr as $a) {
echo $a.' ';
}
echo "\n";
}
//bubbleSort($arr);
function selectionSort($arr) {
$length = count($arr);
/*
for ($outer = 0; $outer < $length - 1; $outer++) {
$min = $arr[$outer];
$minIndex = $outer;
for ($inner = $outer + 1; $inner < $length; $inner++) {
if ($arr[$inner] < $min) {
$min = $arr[$inner];
$minIndex = $inner;
}
}
$tmp = $arr[$outer];
$arr[$outer] = $arr[$minIndex];
$arr[$minIndex] = $tmp;
}
*/
for ($outer = 0; $outer < $length - 1; $outer++) {
$minIndex = $outer;
for ($inner = $outer + 1; $inner < $length; $inner++) {
if ($arr[$inner] < $arr[$minIndex]) {
$minIndex = $inner;
}
}
$tmp = $arr[$outer];
$arr[$outer] = $arr[$minIndex];
$arr[$minIndex] = $tmp;
}
display($arr);
}
//selectionSort($arr);
function insertionSort($arr) {
$length = count($arr);
for ($out = 1; $out < $length; $out++) {
$temp = $arr[$out];
for ($in = $out; $in > 0; $in--) {
if ($arr[$in - 1] < $temp) {
break;
}
$arr[$in] = $arr[$in - 1];
$arr[$in - 1] = $temp;
}
}
display($arr);
}
insertionSort($arr);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment