Last active
November 27, 2020 07:43
-
-
Save uyab/b1a6c009e75a0b91d30ed03dca9b763e to your computer and use it in GitHub Desktop.
Algoritma sorting dadakan
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Niatnya mau diselesaikan dengan algoritma bubble sort, tapi ternyata kok tidak menemui titik cerah, jadinya pakai algoritma dadakan.