Summarizes the algorithm of common centralized sorting
Merge sort
Merge sort is also called merging sort, which is a typical application of divide-and-conquer method. The idea of divide and conquer is to break each problem down into small problems, solve each small problem, and then merge.
The specific merge sort is to decompose a set of unordered numbers by N/2 recursively into children of only one element, an element that is already ordered. These ordered sub-elements are then merged.
The process of merging is to compare two sub-sequences that are already ordered, select the smallest of the two sub-sequences, select the smallest of the two elements and move them from the subsequence
Remove the added to the final result set until two of the subsequence are merged.
The code is as follows:
#!/usr/bin/python Import sys def merge (Nums, first, Middle, last): "' merge ' ' # slice boundary, left closed right open and 0 for start lnums = nums[first:middle+1] rnums = nums[middle+1:last+1] lnums.append (sys.maxint) rnums.append ( Sys.maxint) L = 0 r = 0 for I in range (first, last+1): if LNUMS[L] < Rnums[r]: nums[i] = lnums[l ] l+=1 else: nums[i] = rnums[r] r+=1 def merge_sort (Nums, First, last): "' Merge The sort merge_sort function passes the subscript, not the number of elements "if first < last: middle = (first + last)/2 Merge_sort (Nums, first, middle) Merge_sort (Nums, middle+1, last) merge (Nums, first, middle,last) if __name__ = = ' __main__ ': nums = [ 10,8,4,-1,2,6,7,3] print ' nums is: ', Nums merge_sort (nums, 0, 7) print ' merge sort: ', nums
Stable, time complexity O (nlog N)
Insert Sort
The code is as follows:
#!/usr/bin/python Import sys def insert_sort (a):
"' Insert sort
There is an ordered sequence of data that requires a number to be inserted into the already sorted data series,
However, this data sequence is still ordered after insertion. Initially an element is clearly ordered and then inserted into a
element to the appropriate position, and then insert the third element, and so on
'''
A_len = Len (a) if A_len = 0 and A[j] > key: a[j+1] = a[j] j-=1 a[j+1] = key return a if __name_ _ = = ' __main__ ': nums = [10,8,4,-1,2,6,7,3] print ' nums is: ', Nums insert_sort (nums) print ' Insert Sort: ', nums
Stability, time complexity O (n^2)
Exchange values for two elements in Python, you can write this: a, B = B, A, which is actually because the left and right sides of the assignment symbol are tuples.
(It should be emphasized that in Python, tuples are actually defined by commas "," rather than parentheses.)
Select sort
Select sort (Selection sort) is a simple and intuitive sorting algorithm. It works as follows. The smallest (Large) element is first found in the unsorted sequence and stored in the
The starting position of the sort sequence, and then continues to look for the smallest (large) element from the remaining unsorted elements, and then puts it at the end of the sorted sequence. And so on until the
All elements are sorted.
Import SYS def select_sort (a):
"' Select sort
Each trip selects the smallest (or largest) element from the data element to be sorted,
The order is placed at the end of the ordered sequence, until all the data elements are sorted out.
Select Sort is an unstable sort method.
'''
A_len=len (a) for I in Range (A_len): Select an element of the appropriate size on the #在0-n-1 min_index = i# Record the subscript of the smallest element for J in range (i+1 , A_len): #查找最小值 if (A[j]Instability, time complexity O (n^2)
Hill sort
Hill sort, also known as descending incremental sorting algorithm, Hill Sort is a non-stable sorting algorithm. This method is also known as narrowing the incremental sort, because of the DL. The shell was named after it was introduced in 1959.
First, take an integer less than n D1 as the first increment, dividing all the records of the file into D1 groups. All records with a multiple of D1 are placed in the same group. First in each group to sort;
Then, take a second increment D2<><><><>
< p=""><><><>
Def Shell_sort (a): ' Shell sort ' ' A_len=len (a) gap=a_len/2# increment while gap>0:for i I N Range (A_len): #对同一个组进行选择排序 m=i j=i+1 while J
Instability, time complexity average time O (nlogn) worst time O (n^s) 1<><>< p=""><><>
Heap sort (heap sort)
Definition of "heap": In "heap" with a starting index of 0:
node I right child node in position 2 * i + 24) node I parent node in position floor ((i-1)/2): Note Floor for "rounding" action
Properties of the heap:
The key value of each node must always be greater than (or less than) its parent node
"Maximum heap":
The root node of the heap holds the node with the largest key value. That is, the key value of each node in the heap is always greater than its child nodes.
Move up, Move Down:
When the key value of a node is greater than its parent node, then we are going to move the "move Up" operation, that is, we moved the node to its parent node position,
Instead of getting its parent node to its location, we continue to judge the node until the node is no longer larger than its parent node before stopping "Move up."
Now let's look at the "Move Down" operation. When we change the key value of a node, we need to move it down.
Method:
We first set up a maximum heap (time complexity O (n)), and then each time we only need to exchange the root node with the last node, and then exclude the last location, and then the exchange of the root node of the heap to adjust (Time complexity O (LGN)), that is, the root node "Move Down" operation. The total time complexity for heap sorting is O (NLGN).
The code is as follows:
#!/usr/bin env Python # array numbering starting from 0 def left (i): return 2*i +1 def right (i): return 2*i+2 #保持最大堆性质 take I as root Subtree becomes Max Heap def max_heapify (A, I, heap_size): If heap_size <= 0:return L = Left (i) R = Right (i) largest = i # Select the larger node in the child node if L a[largest]: largest = L if R A[largest]: largest = r If I! = largest: #说明当前节点不是最大的, Move Down a[i], a[largest] = A[largest], a[i] #交换 max_heapify (A, largest, heap _size) #继续追踪下移的点 #print A # build A heap def bulid_max_heap (a): Heap_size = Len (a) if Heap_size >1:no de = HEAP_SIZE/2-1 while node >= 0:max_heapify (A, node, heap_size) node-=1 # heap Row Sequence subscript starting from 0 def heap_sort (a): Bulid_max_heap (a) heap_size = Len (a) i = heap_size-1 while i > 0: A[0],a[i] = A[i], a[0] # The maximum value in the heap is stored in the appropriate position in the array and is exchanged heap_size-=1 # heap Size decrements 1 I-= 1 # The subscript that holds the largest value in the heap Decrement 1 max_heapifY (A, 0, heap_size) if __name__ = = ' __main__ ': a = [ -3, 5, 7, 1, 3, 7] print ' Before sort: ', a He Ap_sort (a) print ' after sort: ', A
Instability, time complexity O (nlog N)
Quick Sort
The fast sorting algorithm, like the merge sort algorithm, is also based on the divide-and-conquer model. Sub-array A[P...R] The three steps of the split process for quick sorting are:
Decomposition: The array A[P...R] into a[p...q-1] and A[Q+1...R] two parts, where each element in a[p...q-1] is less than or equal to a[q] and A[Q+1...R] Each element is greater than or equal to a[q];
Workaround: Sort by recursive call quick Sort, sub-array a[p...q-1] and A[Q+1...R];
Merge: Because two sub-arrays are sorted in place, no additional action is required.
For the beginning of each iteration of dividing partition, X=a[r], for any array subscript k, there are:
1) If p≤k≤i, then a[k]≤x.
2) If i+1≤k≤j-1, then a[k]>x.
3) If k=r, then a[k]=x.
The code is as follows:
#!/usr/bin/env python # fast Sort "'" Division makes a division of the A[r] as the benchmark array, than a[r] small on the left, larger than a[r] on the right to quickly sort the division of the partition process has two methods, one is described above The two pointers index one after the previous step backward scanning method, the other method is two pointers from the first to the middle scan method. "' #p, R is the subscript def partition1 (A, p, r) of array A:" "Method one, two pointer index a previous step backward scanning method" ' x = a[r] I = p-1 j = P While J < R:if A[j] < x:i +=1 A[i], a[j] = A[j], A[i] J + = 1 A[i+1], a[r] = A[r], a[i+1] return i+1 def partition2 (A, P, R): "Two pointers are scanned from the end to the middle" i = P J = r x = a[p] While i = x and I < j:j-=1 A[i] = a[j) while A[i]<=x and I < j:i +=1 A[j] = a[i] a[i] = x return I # Quick sort def quick_s ORT (A, p, R): The worst time complexity for fast sorting is O (N2), and the time complexity is O (NLGN) "if p < r:q = Partition2 (A, p , R) Quick_sort (A, p, q-1) Quick_sort (A, q+1, r) If __name__ = = ' __main__ ': A = [5,-4,6,3,7,11,1,2] print ' before sort: ', a quick_sort (A, 0, 7) print ' After sort: ', a
Unstable, time complexity optimal O (Nlogn) worst time O (n^2)
Say the sequence in Python:
Lists, tuples, and strings are sequences, but what are the sequences and why are they so special? The two main features of a sequence are index operators and slice operators. The index operator allows us to fetch a specific item from the sequence. The slice operator allows us to get a slice of the sequence, i.e. a part sequence, such as: a = [' AA ', ' BB ', ' cc '], print a[0] for the index operation, and print a[0:2] for the slice operation.