Skip to content

Instantly share code, notes, and snippets.

@uyab
Last active November 27, 2020 07:43
Show Gist options
  • Save uyab/b1a6c009e75a0b91d30ed03dca9b763e to your computer and use it in GitHub Desktop.
Save uyab/b1a6c009e75a0b91d30ed03dca9b763e to your computer and use it in GitHub Desktop.
Algoritma sorting dadakan
<?php
$numbers = [10, 9, 13, 100, 0, -10, 23, 2, 4, 17, 1000];
echo 'Original data: '.implode(',', $numbers);
echo '<br>';
echo 'After sort: ';
echo implode(',', bubbleSort($numbers));
function bubbleSort($data)
{
$bucket = [];
// iterasi setiap data
foreach ($data as $index => $value) {
$nominee = $value;
$position = 0;
if (empty($bucket)) {
$bucket[] = $nominee;
} else {
$found = false;
// bandingkan dengan existing element yang sudah tersortir di bucket, jika lebih kecil, berarti
// akan ditaruh di depan element yg bersangkutan
foreach ($bucket as $index2 => $value2) {
if($nominee < $value2) {
$position = $index2;
$found = true;
break;
}
}
// jika tidak ketemu, berarti ditaruh di paling belakang
if(!$found) {
$position = count($bucket);
}
// taruh data ke posisi yang tepat, geser sisanya
array_splice($bucket, $position, 0, [$nominee]);
}
}
return $bucket;
}
@uyab
Copy link
Author

uyab commented Mar 17, 2017

Niatnya mau diselesaikan dengan algoritma bubble sort, tapi ternyata kok tidak menemui titik cerah, jadinya pakai algoritma dadakan.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment