The common sorting algorithms are bubble sort, Merge sort, Quick sort, and so on, all of the Basic Law ideas of sorting are to reduce the size of an infinite scale of data through the algorithm, to guide the final completion of the sorting.
Here to share the buuble sort algorithm, PHP version. Bubble sort does not fit in the case where the data set to be sorted is particularly large, this is just a simple demo, and the data to be sorted is within 10.
The algorithm complexity of the bubbling sorting algorithm, which is caused by 2 extreme cases, is different:
- All datasets are ordered, at this point the algorithm can be optimized by the complexity of the algorithm from O (n^2) to O (n)
- All datasets are unordered, and the complexity of the algorithm is O (n^2)
Beginners seldom consider when writing bubble sort, and if the data itself is an ordered data set, the complexity of the algorithm is O (n^2) if it is not optimized.
Here is the PHP version of the 2 notation:
First Kind
1 functionBubblesort ($arr,$n){2 $swap;//defining the best algorithm for swap resolution3 for($i= 0;$i<$n-1;$i++ ){4 $swap=false; 5 for($j= 0;$j<$n-$i;$j++){ 6 if($arr[$j] >$arr[$j+1]){7 $tmp=$arr[$j];8 $arr[$j] =$arr[$j+1];9 $arr[$j+1] =$tmp;Ten $swap=true; One } A $k++; - } - if($swap==false) the Break1; - } -}
The second Kind
1 functionNewbubblesort ($arr,$n){2 Do {3 $sorted= 1;4--$n;5 for($i= 0;$i<$n;$i++){6 if($arr[$i] >$arr[$i+1]){7 $t=$arr[$i];8 $arr[$i] =$arr[$i+1];9 $arr[I+1] =$t;Ten $sorted= 0; One } A } -} while(!$sorted); -}
Optimizes the bubble sorting algorithm by defining a flag bit.
Bubble sort (Bubble sort)