The summary of Python sort algorithm and the detailed example _python

Source: Internet
Author: User
Tags in python

Summed up the common centralized sorting algorithm

Merge sort

Merge sort is also called merging sort, which is a typical application of partition method. The idea of divide-and-conquer is to decompose each problem into small problems, resolve each small problem, and then merge.

The specific merge sort is to decompose a group of unordered numbers into N/2 recursively, one element is already ordered. " These ordered child elements are then merged.

The merging process is to compare the smallest of the two subsequence to the two sorted subsequence, select the smallest of the two elements and move it from the subsequence

Remove the add to final result set until two subsequence merge complete.

The code is as follows:

#!/usr/bin/python 
Import sys 
 
def merge (Nums, first, Middle, last): 
  "' merge ' ' 
  # slice boundary, left open and right and 0 to 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 (last+1): 
    if LNUMS[L] < Rnums[r]: 
      nums[i] = lnums[ L] 
      l+=1 
    else: 
      nums[i] = rnums[r] 
      r+=1 
def merge_sort (Nums, I, last): 
  "' Merge The sort
  merge_sort function is passed the subscript, not the number of elements
  ' if I < last 
  : 
    middle = (A/last)/2 
    Merge_sort (Nums, middle) 
    Merge_sort (Nums, middle+1, last) 
    merge (Nums, A, 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

Stability, time complexity O (nlog N)

Insert Sort

The code is as follows:

#!/usr/bin/python 
Importsys 
 
Definsert_sort (a): 
  ' Insert sort
  has an ordered sequence of data that requires inserting a number in the sorted sequence of data,
  However, this sequence of data is still in order after the insertion is required. The first element is clearly ordered, then inserts an
  element into the appropriate position, and then inserts a 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)

Swap values for two elements 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 sort algorithm. Its working principle is as follows. First, the smallest (large) element is found in the unordered sequence, which is stored in the

The starting position of the sort sequence, and then continue looking for the smallest (large) element from the remaining unordered elements, and then drop it at the end of the sorted sequence. And so on, until the

All elements are sorted and finished.

Import SYS 
def select_sort (a): 
  ' Select the sort 
  each trip selects the smallest (or largest) element from the data element to be sorted,
  in the order that it is placed at the end of the ordered series, Until all the data elements to be sorted are finished.
  Selecting a sort is an unstable sort method.
  ' 
  A_len=len (a) 
  for I in Range (A_len): #在0-n-1 Select the element of the corresponding size 
    Min_index = i# the subscript for J to record the smallest element 
    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 S ORT: ', a  
  select_sort (a)  
  print ' After sort: ', a

Instability, time complexity O (n^2)

Hill sort

Hill sort, also called the descending increment sort algorithm, Hill sort is a non stable sort algorithm. The method is also called narrowing the incremental order, due to DL. The shell was named after it was introduced in 1959.

First, take an integer d1 less than n as the first increment, dividing the entire record of the file into D1 groups. All records with a multiple distance of D1 are placed in the same group. First in each group of sorting;

Then, take the second increment D2

Import SYS 
def shell_sort (a): 
  ' shell sort 
  ' 
  a_len=len (a) 
  gap=a_len/2# Delta 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 adds 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

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

Heap sort (Heap sort)

Definition of "heap": In "heap" with starting index 0:

Node I of the right child node at position 2 * i + 24) node I of the parent node in position floor ((i–1)/2): Note floor means "rounding" operation

The characteristics of the heap:

The key value of each node must always be greater than (or less than) its parent node

"Max 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 a node's key value is greater than its parent node, then we are going to move up the action, that is, we move the node to its parent node and let its parent node in its place, and then we continue to judge the node until the node is no longer larger than its parent node to stop moving up.

Now let's take a 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)), then each time we only need to swap the root node with the last location, and then exclude the last position, and then the exchange of the root node after the heap adjustment (Time complexity O (LGN)), that is, the root node to "Move Down" operation. The total time complexity of heap sorting is O (NLGN).

The code is as follows:

#!/usr/bin env Python # array numbering starting with 0 Def left (i): return 2*i +1 def right (i): return 2*i+2 #保持最大堆性质 make the subtree with I root become 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: #说明当前节点不是最大的, under Move A[i], a[largest] = A[largest], a[i] #交换 max_heapify (A, largest, heap_size) #继续追踪下移的点 #print A # build A bunch of def BU Lid_max_heap (a): Heap_size = Len (a) if heap_size >1:node = HEAP_SIZE/2-1 while node >= 0:ma  
  X_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 location and exchanged heap_size-=1 # heap Small descending 1 I-= 1 # The subscript descending the maximum of the storage heap is 1 max_heapify (A, 0, heap_size) if __name__ = = ' __main__ ': a = [10,-3, 5, 7, 1, 3, 7] print ' BeFore sort: ', a Heap_sort (a) print ' after sort: ', a
 

Unstable, time complexity O (nlog N)

Quick Sort

The fast sort algorithm is also based on the partition mode, as is the merging sort algorithm. Sub-array A[P...R] The three steps of a fast sorting process are:

Decomposition: The array a[p...r] divided into a[p...q-1] and A[Q+1...R] two parts, where each element in a[p...q-1] is less than equal to a[q] and A[Q+1...R] Each element is greater than or equal to a[q];

Resolve: Sort by recursive invocation of fast ordering, a[p...q-1 of pairs] and A[Q+1...R];

Merging: Because two arrays are sorted in place, no extra action is required.

For the beginning of each iteration of the 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 # Quick sort ' divide to satisfy a[r] as the base array for a division, smaller than A[r] on the left, bigger than a[r to the right. There are two ways to quickly sort the divide-and-conquer partition process, one of which is described above
The two pointer index is a method that scans backwards and forwards, and another method is to scan two pointers from the first to the middle. "#p, R is an array of subscript def partition1 (A, p, r):" "Method one, two pointers index one after the previous step backward scan method ' ' x = a[r] i = p-1 j = P W  
  Hile 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): "The method of" two pointers scanned from end to end "I = P j = r x = a[p] While i = x A 
  nd 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 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)

Next, 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 the sequence are index operators and slicing operators. The index operator allows us to grab a specific item from the sequence. The slice operator allows us to get a slice of the sequence, which is part of a sequence, such as: a = [' AA ', ' BB ', ' cc '], print a[0] for indexing operations, and print a[0:2] for slicing operations.

Hope that this article to grasp the knowledge of Python algorithm sequencing, thank you for your 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.