PHP Four basic Sort algorithm example _php instance

Source: Internet
Author: User

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.

Code implementation:

$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 + +)
 {//The layer loop is used to control the number of times a number needs to be compared for each round
 ($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.

Code implementation:

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 minimum value
 $p = $i;
 for ($j = $i +1; $j < $len; $j + +) {
  //$arr [$p] is the currently known minimum
  if ($arr [$p] > $arr [$j]) {
  //compare, find smaller, record the minimum value position , and the next comparison is made with a known minimum value.
  $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;
 }
 }
 Returns the final result return
 $arr;
}

3. Insert Sort

Thought analysis: In order to sort of a group of numbers, assuming that the previous number is already in order, now to the number of n into the previous ordered number, so that the number of n is also ranked in order. Repeat the loop until all the order is sorted.

Code implementation:

function Insertsort ($arr) {
 $len =count ($arr); 
 For ($i =1, $i < $len; $i + +) {
 $tmp = $arr [$i];
 Inner loop control, comparing and inserting for
 ($j = $i-1; $j >=0; $j-) {
  if ($tmp < $arr [$j]) {
  //find inserted elements smaller, swap positions, swap the elements behind with the preceding elements
  $arr [$j +1] = $arr [$j];
  $arr [$j] = $tmp;
  } else {
  //If you encounter an element that does not need to be moved, because it is already sorted to be an array, the front does not need to be compared again. Break
  ;
 }
 }} return $arr;
}

4. Quick Sort

Analysis: Select a datum element, usually select the first element or the last element. Through a scan, the backlog sequence is divided into two parts, smaller than the Datum element, and one part greater than or equal to the datum element. At this point, the datum element is in the correct position after it is sorted, and then the same method is used to recursively sort the two parts of the partition.

Code implementation:

function QuickSort ($arr) {
 ///First determine whether the need to continue
 $length = count ($arr);
 if ($length <= 1) {return
 $arr;
 }
 Select the first element as the benchmark
 $base _num = $arr [0];
 Iterate over all elements except the ruler, put into two arrays by size relationship
 //Initialize two arrays
 $left _array = Array ();//less than
 $right _array = Array ();//greater Than the datum For
 ($i =1 $i < $length $i + +) {
 if ($base _num > $arr [$i]) {
  //put an array on the left
  $left _array[] = $arr [$i];
 else {
  //put to the right
  $right _array[] = $arr [$i]
 ;
 }
 And then to the left and right of the array to do the same sort of processing method recursively call this function
 $left _array = Quick_sort ($left _array);
 $right _array = Quick_sort ($right _array);
 Merge return
 Array_merge ($left _array, Array ($base _num), $right _array);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.