Many people have said that the algorithm is the core of the program, the quality of the algorithm determines the process. As a primary phper, although little contact with algorithmic aspects. But for the basic sorting algorithm or should be mastered, it is the necessary tool for program development. This article introduces bubble sort, insert sort, select Sort, fast sort four basic algorithms, analyze the idea of the algorithm.
Premise: Bubble sort method, fast sorting method, select sorting method, insert Sort method to sort the values in the following arrays in order from small to large.
$arr (1,43,54,62,21,66,32,78,36,76,39);
1. Bubble sort
Train of thought analysis: In order to sort of a group of numbers, the current has not yet lined up the sequence, from the next two consecutive number of adjacent to the comparison and adjustment, so that the larger number to sink, smaller upward. That is, when the number of adjacent numbers in two is found to be the opposite of their sorting requirements, they are interchanged.
- $arr =array (1,43,54,62,21,66,32,78,36,76,39);
- function Bubblesort ($arr)
- {
- $len =count ($arr);
- This layer loops the number of wheels that need to bubble
- for ($i =1; $i < $len; $i + +)
- {//This layer loop is used to control the number of times a number needs to be compared per round
- for ($k =0; $k < $len-$i; $k + +)
- {
- if ($arr [$k]> $arr [$k +1])
- {
- $tmp = $arr [$k +1];
- $arr [$k +1]= $arr [$k];
- $arr [$k]= $tmp;
- }
- }
- }
- return $arr;
- }
2. Select sort
Analysis: In the number of groups to be sorted, select the smallest number and the first position of the number exchange. Then, in the remaining number, find the smallest interchange with the second position, so that it loops to the penultimate number and the last number comparison.
- function Selectsort ($arr) {
- Double loop complete, outer control wheel number, inner layer control comparison times
- $len =count ($arr);
- For ($i =0 $i < $len-1; $i + +) {
- Assume the position of the smallest value first
- $p = $i;
- for ($j = $i +1; $j < $len; $j + +) {
- $arr [$p] is the currently known minimum value
- if ($arr [$p] > $arr [$j]) {
- Compare, find a smaller, recorded position of the minimum value, and compare it with a known minimum value for the next comparison.
- $p = $j;
- }
- }
- The position of the current minimum value has been determined and saved to the $p. If the location of the lowest value is found to be different from the current assumed position $i, the position is interchangeable.
- if ($p!= $i) {
- $tmp = $arr [$p];
- $arr [$p] = $arr [$i];
- $arr [$i] = $tmp;
- }
- }
- Return final Result
- return $arr;
- }