Summary and example of Python sorting algorithm

Source: Internet
Author: User
This article mainly introduces the Python sorting algorithm summary and examples of relevant information, the need for friends can refer to the following

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 sort  The 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 Importsys  Definsert_sort (a):   "The insertion sort  has 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. At first, an element is clearly ordered, then an element is inserted  into place, then a third element is inserted, and then  "' '   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, placing the order at the end of the ordered sequence  until all the data elements to be sorted are exhausted.  Select Sort is an unstable sort method.  "'   A_len=len (a) for   I in range (A_len): Select the appropriate size element on the #在0-n-1     min_index = i# Record the subscript for the smallest element for     J in range (I+1, A_len): #查找最小值       if (A[j]<a[min_index]):         min_index=j     if min_index! = I: #找到最小元素进行交换       a[i],a[ Min_index] = a[min_index],a[i]  if __name__ = = ' __main__ ':   a = [ -3, 5, 7, 1, 3, 7]    print ' before sort: ', A    select_sort (a)    print ' After sort: ', a

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

Import sys def shell_sort (a):   ' shell sort   ' '   a_len=len (a)   gap=a_len/2# increment while   gap>0: For     i in range (A_len): #对同一个组进行选择排序       m=i       j=i+1 while       j<a_len:         if a[j]<a[m]:           m=j         J+=gap#j add Gap       if m!=i:         a[m],a[i]=a[i],a[m]     gap/=2  if __name__ = = ' __main__ ':   a = [10,-3, 5, 7 , 1, 3, 7]    print ' before sort: ', a    shell_sort (a)    print ' After sort: ', a

Instability, time complexity average time O (nlogn) worst time O (n^s) 1

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, then we are going to move the "up" operation, that is, we moved the node to its parent node, and let its parent node to its location, and then we continue to judge the node until the node is no longer greater than its parent node to stop "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 #保持最大堆性质 make the subtree with the root of I become the largest heap def m   Ax_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[larges T] = A[largest], a[i] #交换 max_heapify (A, largest, heap_size) #继续追踪下移的点 #print A # Build Def bulid_max_heap (a): heap_s      ize = Len (a) if heap_size >1:node = HEAP_SIZE/2-1 while node >= 0:max_heapify (A, node, heap_size) Node-=1 # heap sort 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 of the maximum value in the storage heap is decremented by 1 m Ax_heapify (A, 0, heap_size) if __name__ = = ' __main__ ': a = [ten, -3, 5, 7, 1, 3, 7] print ' Before sort: ', a heap_so RT (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 distinction between the a[r] as the base of the array, than a[r] small on the left,  than A[r] large on the right to quickly sort the division of the partition process has two methods, One is the two pointer index mentioned above one after the step backward scanning method, the other method is two pointers from the first to the middle scanning method. "' #p, R is the subscript of array A def partition1 (A, p, r):   " "   method one, two pointer index one after the 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 from the first to the middle of the method of scanning" "   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_sort (A, P, r):   ""    the worst time complexity for quick sorting is O (N2), the usual time complexity For 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.

Hope that through this article grasp the Python algorithm sequencing knowledge, thank you for the support of this site!

Related Article

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.