Apr
This is one question that came out during PHP Programming Interview.
Displaying random number from 1-100 and is sorted as much as the number who entered. eg input 8 results:
Show eight times a random number from 1-100: 5, 84, 97, 19, 71, 31, 45, 90
Result sequence of random numbers from small to large: 5, 19, 31, 45, 71, 84, 90, 97
so,i’m gonna use bubble sort for sorting, but what is bubble sort? Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements “bubble” to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort.(Source:http://en.wikipedia.org/wiki/Bubble_sort)
Pseudocode implementation
procedure bubbleSort( A : list of sortable items ) defined as:
n := length( A )
do
swapped := false
for each i in 0 to n - 1 inclusive do:
if A[ i ] > A[ i + 1 ] then
swap( A[ i ], A[ i + 1 ] )
swapped := true
end if
end for
n := n - 1
while swappedend procedure
sample implementation in PHP:
if(isset($_POST['nilai']))
$a=$_POST['nilai'];
define(MAX_NUMBER,$a);
echo "Tampilkan bilangan acak $a kali dari 1 - 100 : \n";
for($x = 0; $x <= MAX_NUMBER-1; $x++)
$ran[$x] = rand(1, 100);
echo $ran[$x] ."\n";
for($x = 0; $x < MAX_NUMBER-2; $x++) {
for($y = 0; $y < MAX_NUMBER-2-$x; $y++) {
if($ran[$y] > $ran[$y+1]) {
$hold = $ran[$y];
$ran[$y] = $ran[$y+1];
$ran[$y+1] = $hold;
}
}
}
echo "Hasil urutan bilangan acak dari yang kecil ke yang besar :";
for($x = 0; $x < MAX_NUMBER-1; $x++)
print $ran[$x] ."," . "\n"; ?>

