Fast sorting is often used because of the efficiency of the sorting efficiency in several sorting methods of the same O (N*logn).
The basic idea of this method is:
1. First, a number is taken from the series as the base number.
2. The partitioning process, which puts the number of large numbers on its right, is less than or equal to its number to the left.
3. Repeat the second step for the left and right intervals until there is only one number for each interval.
Now it's a neat row with an example.
For example, there is an array:
6 2 4) 5 3
The first step: Select a base number, do not be frightened by this noun, you can think of it as a relatively large number, because the sort is the size of the comparison,
For example, I choose the last number 3 as the base number, and then compare the number of the array and 3, compared to 3 small left, than the 3 large put to the right, this has the following results:
2 3 6) 4 5
The second step: determine the number of intervals, after the first step after the left interval only a number, no number and then compared to it, so do not need to repeat the operation, the right interval is:
6 4 5
Repeat the first step and select 5 as the base number to get the comparison result:
4 5 6
So that the left and right sides of the interval are only one number, which marks the completion of the order, and finally the integration of all the intervals to get sorted results:
2 3 4) 5 6
def quick_sort (array): less = []; greater = [] If Len (array) <= 1: return array pivot = Array.pop ()
for x in array: if x <= pivot:less.append (x) else:greater.append (x) return Quick_sort (less) + [pivot] + Quick_sort (greater) List = [2,4,2,6,7,8,1]
Print Quick_sort (list)
[1, 2, 2, 4, 6, 7, 8]
Compared to C, C #, Java and the like is not much simpler ^.^
TIP: Quick sort of Go heavy
as follows, simply modify the set to a single-valued element, where we use Python3 to demonstrate:
#-*-Coding:utf-8-*- import random L = [2, 3, 8, 4, 9, 5, 6, 5, 6,, one, 2] def qsort (L): If Len ( L) <2:return l pivot_element = Random.choice (l) small = [i-I in L if i< pivot_element] #medium = [i For I in L if i==pivot_element] large = [i-I in L if i> pivot_element] return qsort (small) + [pivot_element ] + qsort (Large)
Output:
It can also be used directly, set (set) for sorting and de-weight.