(919) 964-9842
(919) 964-9842

Hackerrank in PHP: Sorting - Bubble Sort

The beauty with this problem is that they give you the bubble sort algorithm already. You just need to translate it into your language of choice (in this case, PHP), add in a counting mechanism, and find the first and last element of the array once all the swapping is done.

For this problem, we are given a bubble sort algorithm and then asked to determine how many swaps took place, as well as the first and last element of the final array. Let's do it!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Complete the countSwaps function below.
function countSwaps($a) {
    $numSwaps = 0;

    for ($i = 0; $i < count($a); $i++) {
        for ($j = 0; $j < count($a) - 1; $j++) {
            // Swap adjacent elements if they are in decreasing order
            if ($a[$j] > $a[$j + 1]) {
                $temp = $a[$j];
                $a[$j] = $a[$j + 1];
                $a[$j + 1] = $temp;

                $numSwaps++;
            }
        }
    }

    $firstElement = $a[0];
    $lastElement = $a[count($a) - 1];

    echo "Array is sorted in $numSwaps swaps.\n";
    echo "First Element: $firstElement\n";
    echo "Last Element: $lastElement";
}

Everything is essentially the same as the bubble sort algorithm goes, I only added a numSwaps variable to count the swaps, and then parsed out the swap() function to PHP terms. Essentially, throw the value in a temp variable so you can swap the placement without losing the value. To get the first and last value, I picked out the values from the final array using the first indicator of zero, and the count from before (minus 1, because the array starts at zero).

Pretty straightforward!

Categories: Development

Leave a Reply

Your email address will not be published. Required fields are marked *