Just for fun, let's share codes for Bubble Sort algorithm in any programming languages here.
PHP
<?php
$data = array(
'Perlis', 'Kedah', 'Pulau Pinang',
'Perak', 'Selangor', 'Wilayah Persekutuan',
'Negeri Sembilan', 'Melaka', 'Johor',
'Pahang', 'Terengganu', 'Kelantan',
'Sarawak', 'Sabah');
for ($i = 0; $i < count($data); $i++) {
for ($j = count($data) - 1; $j > $i; $j--) {
if ($data[$j] < $data[$j - 1]) {
$t = $data[$j];
$data[$j] = $data[$j - 1];
$data[$j - 1] = $t;
}
}
}
print '<pre>' . print_r($data, true) . '</pre>';
?>
chongkeat
02-12-2008, 03:58 PM
I'm not familiar with PHP, but from what I see, you:
---------
Create an array.
do for number of data in array (variable A)
{
do for number of data - 1, while it is larger than A (variable B)
{
switch the data in positions array A & B if... (OK, now I'm confused.)
--------
A bubble sort is kinda like stepping through a list and sorting each one through? Like this?
156423
154236
142356
123456
And I don't really know this part. I know we shouldn't be spoonfed, but can you please explain with comments or something?
if ($data[$j] < $data[$j - 1]) {
$t = $data[$j];
$data[$j] = $data[$j - 1];
$data[$j - 1] = $t;
You're sorting according to the word length, right? So, I guess $data[] is something like a letter count?
*Looking up Bubble Sort (http://en.wikipedia.org/wiki/Bubble_sort)*
The sorting algorithm is called "Bubble Sort" because smaller (or larger) elements move towards the end of the sequence, just like how bubble rises from the bottom of a lake to the surface.
let's say i have 2,4,3,5,1.
first step, i compare 1 to 5, 1 is less than 5 so we swap: 2,4,3,1,5
then compare 1 to 3, 1 is less than 3 so swap again: 2,4,1,3,5
then 1 to 4, again, swap: 2,1,4,3,5
then 1 to 2, swap: 1,2,4,3,5
see how 1 'bubbles' towards the left since it's smaller than all other elements?
now 1 is confirmed as the smallest element in the sequence.
let's continue,
compare 5 to 3, no swap: 1 --- 2,4,3,5
3 to 4, swap: 1 --- 2,3,4,5
3 to 2, no swap: 1 --- 2,3,4,5
now 2 is confirmed as smallest from what's left thus: 1,2 --- 3,4,5
continue until all elements are confirmed as ordered.
implementing it into the code, the outer loop for ($i ... ) handles the ordered vs unordered elements while the inner loop for ($j ... ) handles the actual comparison and swapping.
vBulletin® v3.7.6, Copyright ©2000-2013, Jelsoft Enterprises Ltd.