Home >Backend Development >PHP Tutorial >A simple example of bubble sorting in PHP, php bubble sorting_PHP tutorial

A simple example of bubble sorting in PHP, php bubble sorting_PHP tutorial

WBOY
WBOYOriginal
2016-07-12 08:50:45963browse

A simple example of bubble sorting in PHP, php bubble sorting

1. First, we must figure out what bubble sorting is. If we don’t understand the principle of bubble sorting, we You can't write code.

The basic concept of Bubble Sort is: compare two adjacent numbers in sequence, put the decimal in the front and the large number in the back. That is, in the first pass: first compare the first and second numbers, put the decimal first and the large number last. Then compare the second number and the third number, put the decimal in front and the large number in the back, and continue like this until comparing the last two numbers, put the decimal in front and the large number in the back. This is the end of the first trip, leaving the largest number at the end. In the second pass: still start the comparison from the first pair of numbers (because it may be due to the exchange of the second number and the third number that the first number is no longer smaller than the second number), put the decimal first, and the large number After placing it, the comparison is continued until the second to last number (the first to last position is already the largest). At the end of the second pass, a new maximum number is obtained at the second to last position (in fact, it is the largest number in the entire sequence). The second largest number). Continue like this and repeat the above process until the sorting is finally completed.

PHP implementation code:

<&#63;php
  
  //冒泡排序方法

  function bubblesort(&$arr){
      //定义一个变量保存交换的值
    $temp =0;
    for($i=0;$i<count($arr);$i++){
      
      for($j=0;$j<count($arr)-$i-1;$j++){
            
        if($arr[$j]>$arr[$j+1]){
          //如果前面的那个数大于后面的那个数,那么他们就进行交换
          $temp=$arr[$j];
          $arr[$j]=$arr[$j+1];
          $arr[$j+1]=$temp;
        }
      }      
    }
  }

  $arr=array(100,99,200,5,-4,6,-7);
  bubbleSort($arr);
  print_r($arr);  //数组是值传递,所以传递的时候加个&符号就是地址传递,改变外部变量


&#63;>

The above simple example of bubble sorting in PHP is all the content shared by the editor. I hope it can give you a reference, and I hope you will support Bangkejia more.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1133070.htmlTechArticleA simple example of bubble sorting in PHP, php bubble sorting 1. First, we must understand what bubble is Sorting, without understanding the principle of bubble sort, we cannot write code. Bubbly steak...
Statement:
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