PHP Interview: write common sorting algorithm, and achieve a bubble sort with PHP

Interview, test sites involved in related algorithms are not many, because the algorithm is very simple PHP involved in practical work, but also appear in some of the written examination for basic study of the interviewer, which examine the most is the sorting algorithm, and to understand and implement bubble sort is the top priority.

Common sorting algorithm

  • Bubble Sort
  • Direct insertion sort
  • Shell sort
  • Selection Sort
  • Heapsort
  • Merge sort

Often questions: which algorithm is faster and more efficient? (If there are merge sort preference, if not, select Quick Sort)


Bubble sort of principle

Two adjacent numbers are compared, if in reverse order on the exchange or not exchange.

Time complexity: O (n ^ 2)
between the space complexity: O (1)


Bubble sort of realization

for ($i=0, $c=count($arr); $i < $c ; $i++) {
  for ($j=0; $j < $c-1; $j++) {
    if($arr[$j] > $arr[$j+1]){
      $temp = $arr[$j];
      $arr[$j] = $arr[$j+1];
      $arr[$j+1] = $temp;
    }
  }
}

Guess you like

Origin www.cnblogs.com/jiaoran/p/12558252.html