uyab
3/17/2017 - 8:14 AM

Algoritma sorting dadakan

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;
}