Skip to content

Instantly share code, notes, and snippets.

@ahanafi
Created December 12, 2021 12:21
Show Gist options
  • Save ahanafi/6420b0e38b043544635b046dafd1e351 to your computer and use it in GitHub Desktop.
Save ahanafi/6420b0e38b043544635b046dafd1e351 to your computer and use it in GitHub Desktop.

Revisions

  1. ahanafi created this gist Dec 12, 2021.
    30 changes: 30 additions & 0 deletions min-max-array.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    <?php
    /*
    * TODO: Cari Nilai terkecil dan terbesar dari suatu array tanpa menggunakan fungsi built in dari bahasa program yang digunakan
    * */

    /*
    * Solusi: Menggunakan logika bubble sort, kemudian dapat kan data index pertama dan terakhir
    * */

    function solutions(array $numbers)
    {
    $lenthArray = count($numbers);
    for ($i = 0; $i < $lenthArray; $i++) {
    for($j = 0; $j < $lenthArray - 1; $j++) {
    if($numbers[$j] > $numbers[$j+1]) {
    $temporary = $numbers[$j];
    $numbers[$j] = $numbers[$j+1];
    $numbers[$j+1] = $temporary;
    }
    }
    }

    $smallest = $numbers[0];
    $highest = $numbers[$lenthArray - 1];

    return "The smallest number is " . $smallest . " and the highest is " . $highest . PHP_EOL;
    }

    echo solutions([64, 34, 25, 12, 22, 11, 90]);
    echo solutions([6,37,2,100,27,18,3,98,1,74,89,923]);