Home > Article > Backend Development > Sorting algorithm: PHP version quick sort, bubble sort_PHP tutorial
1. Quick sort
1. Introduction
Quick sort is a sorting algorithm developed by Tony Hall. On average, sorting n items requires O(n log n) comparisons. In the worst case, O(n2) comparisons are required, but this situation is uncommon. In fact, quicksort is often significantly faster than other Ο(n log n) algorithms because its inner loop can be implemented efficiently on most architectures.
Quick sort uses the divide and conquer strategy to divide a sequence (list) into two sub-series (sub-lists).
2. Steps
Pick an element from the sequence, called the "pivot",
Reorder the sequence, all elements smaller than the pivot value are placed in front of the pivot, and all elements smaller than the pivot value are placed in front of the pivot. The one with the larger value is placed behind the base (the same number can go to either side). After this partition exits, the base is in the middle of the sequence. This is called a partition operation.
Recursively sort the subarray of elements smaller than the base value and the subarray of elements greater than the base value.
3. Code implementation
';<p> print_r(quickSort(array(1,4,22,5,7,6,9)));<br> print '';
2. Bubble Sort
1. Introduction
Bubble Sort (Bubble Sort, translated in Taiwan as: bubble sort or bubble sort) is a simple sorting algorithm. It repeatedly walks through the sequence to be sorted, comparing two elements at a time and swapping them if they are in the wrong order. The work of visiting the array is repeated until no more exchanges are needed, which means that the array has been sorted. The name of this algorithm comes from the fact that smaller elements will slowly "float" to the top of the array through swapping.
2. Step
Compare adjacent elements. If the first one is bigger than the second one, swap them both.
Do the same for each pair of adjacent elements, starting with the first pair and ending with the last pair. At this point, the last element should be the largest number.
Repeat the above steps for all elements except the last one.
Continue repeating the above steps for fewer and fewer elements each time until there are no pairs of numbers to compare.
3. Code implementation
';<br> print_r(bubbingSort(array(1,4,22,5,7,6,9))); print '';
4. Sorting process
http://www.bkjia.com/PHPjc/751510.html