Home > Backend Development > PHP Problem > How to implement bubble sort algorithm in php

How to implement bubble sort algorithm in php

PHPz
Release: 2023-03-24 10:24:01
Original
2737 people have browsed it

Bubble sort algorithm is a basic sorting algorithm and one of the simplest sorting algorithms. Its principle is very simple, it is to repeatedly traverse the array that needs to be sorted, and compare two adjacent elements each time. If their order is wrong, swap them until the largest element is found, and then repeat the above operation. Until the entire array is sorted.

The following is how to implement the bubble sort algorithm in PHP:

  1. Create an array and assign a value to the array
$array = array(5, 3, 8, 1, 6, 7, 2, 4);
Copy after login
  1. Write the bubble sort algorithm Bubble sort function
function bubble_sort($array) {
    $count = count($array);
    for($i=0;$i<$count-1;$i++) {
        for($j=0;$j<$count-$i-1;$j++) {
            if($array[$j]>$array[$j+1]) {
                $temp = $array[$j];
                $array[$j] = $array[$j+1];
                $array[$j+1] = $temp;
            }
        }
    }
    return $array;
}
Copy after login
  1. Call the bubble sort function and output the sorted array
$result = bubble_sort($array);
print_r($result);
Copy after login

The complete code is as follows:

$array = array(5, 3, 8, 1, 6, 7, 2, 4);

function bubble_sort($array) {
    $count = count($array);
    for($i=0;$i<$count-1;$i++) {
        for($j=0;$j<$count-$i-1;$j++) {
            if($array[$j]>$array[$j+1]) {
                $temp = $array[$j];
                $array[$j] = $array[$j+1];
                $array[$j+1] = $temp;
            }
        }
    }
    return $array;
}

$result = bubble_sort($array);
print_r($result);
Copy after login

The output results are as follows:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
)
Copy after login

The above is the complete method of implementing the bubble sort algorithm in PHP.

The above is the detailed content of How to implement bubble sort algorithm in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template