简体   繁体   中英

Bubble sort array, how can I make this php bubble sort code better or more effective?

how can I make this php bubble sort code better or more effective?

// bubble sort for $AR 
for($i = count($AR)-1 ; $i <= 1; $i--) 
   for($j = 0; $j < $i; $j++) {
      if($AR[$j] > $AR[$j+1]) {
          $t = $AR[$j];
          $AR[$j] = $AR[$j+1];
          $AR[$j+1] = $t;
       } //if
   } //for j 

Algorithms are algorithms, if you make some modifications and achieve a better performance you won't be using the Bubble sorting algorithm anymore, because it would have changed.

If you want a increase performance you need to change the algorithm, Quick Sort is generally considered to be the best sorting one. As an example of the implementation in php:

// QuickSort Algorithm function
function quickSort(array $array) {
    if (count($array) == 0) {
        return $array;
    }
    $pivot = $array[0];
    $left = $right = array();
    for($i = 1; $i < count($array); $i ++) {
        if ($array[$i] < $pivot) {
            $left[] = $array[$i];
        } else {
            $right[] = $array[$i];
        }
    }
    return array_merge(quickSort($left), array(
            $pivot
    ), quickSort($right));
} 

Of course, it always depends on the situation, if you optimize it you would be basing your code on that algorithm but not making bubble algorithm better or more effective .

Check this post , where is really well documented almost every type of sorting in php.

Hope this helps you!

If you want to make this one more efficient, you could put the

count($AR)-1

in your for loop into a variable, since it would be done at every iteration. Well it's a small speedup since count is O(1), but it's something..
Sidenote: there would be side effects if you modify the array while looping over it in php7 example:

$a = [1,2,3,4];  
$b = 1;   
for ($i = 0;$i<count($a);$i++) {  
unset($a[$i]);  
echo $i . "\n";  
}  
var_dump($a);  

output:

0
1

-:9:
array(2) {
[2] =>
int(3)
[3] =>
int(4)
}

note how it only goes to 1

As it stands, your code won't do anything at all. You got the first loop condition wrong. With that corrected, it looks like a perfectly fine bubble sort.

// bubble sort for $AR 
for($i = count($AR)-1 ; $i >= 1; $i--) 
   for($j = 0; $j < $i; $j++) {
      if($AR[$j] > $AR[$j+1]) {
          $t = $AR[$j];
          $AR[$j] = $AR[$j+1];
          $AR[$j+1] = $t;
       } //if
   } //for j 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM