Python code sample Summary for implementing various sorting algorithms

Source: Internet
Author: User
In Python practice, we tend to encounter sorting problems, such as the sort of scoring of search results (without the presence of search engines like Google), and of course, there are countless examples. The data structure also takes a lot of space to explain the sort. Some time ago, because of the need, I reviewed the sorting algorithm, and Python implemented a variety of sorting algorithms, put here as a reference.

The simplest sort has three kinds: insert sort, select sort and bubble sort. These three sorts are relatively simple, their average time complexity is O (n^2), here the principle is not added to repeat. Post the source code.

Insert Sort:

def insertion_sort (sort_list):  Iter_len = Len (sort_list)  if Iter_len < 2:    return sort_list for  i in  Range (1, Iter_len):    key = Sort_list[i]    j = i-1 while    J >= 0 and Sort_list[j] > key:      sort_list[j+1] = Sort_list[j]      J-= 1    sort_list[j+1] = key  return sort_list

Bubble Sort:

def bubble_sort (sort_list):  Iter_len = Len (sort_list)  if Iter_len < 2:    return sort_list for  i in Range (iter_len-1):    for J in Range (iter_len-i-1):      if SORT_LIST[J] > sort_list[j+1]:        sort_list[j], SORT_LIST[J+1] = sort_list[j+1], sort_list[j]  return sort_list

Select Sort:

def selection_sort (sort_list):  Iter_len = Len (sort_list)  if Iter_len < 2:    return sort_list for  i in Range (iter_len-1):    smallest = sort_list[i] location    = i    -j in range (I, Iter_len):      if SORT_LIST[J] < smallest:        smallest = sort_list[j] location        = J    If I! = Location:      sort_list[i], sort_list[ Location] = Sort_list[location], Sort_list[i]  return sort_list

Here we can see a sentence like this:

Sort_list[i], sort_list[location] = Sort_list[location], sort_list[i]
Students who do not know Python may find it strange, yes, to exchange two numbers, usually in other languages if you want to exchange A and B values, you often need an intermediate variable temp, first assigns a to temp, then assigns B to a, and finally assigns temp to B. But in Python you can write this: a, B = B, A, in fact, this is 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).

The average time complexity of O (NLOGN) algorithm is: merge sort, heap sort and quick sort.

Merge sort. For a subsequence, divide into two parts, compare the first element of two parts, the small one pops up, and then repeat the process. For the sequence to be sorted, the middle value is divided into the left and right two sequences, and then recursively called for each sub-sequence. The source code is as follows, because of the tool function, it is written in the callable class:

Class Merge_sort (object): Def _merge (self, alist, p, Q, r): left = alist[p:q+1] right = alist[q+1:r+1] for i in Range (p, r+1): If Len (left) > 0 and Len (right) > 0:if left[0] <= right[0]: alist[i] = left. Pop (0) else:alist[i] = Right.pop (0) Elif len (right) = = 0:alist[i] = Left.pop (0) elif le N (left) = = 0:alist[i] = Right.pop (0) def _merge_sort (self, alist, p, r): if P
 
  

The heap sort is built on the data structure--the heap. There is no introduction to the basic concepts of heaps and how heaps are stored. Here a list is used to store the heap (as with the array store), and for the element at position I, the left child of the 2i+1 position, 2i+2 is the right child, similar to the parent element of the element.

First we write a function that, for a subtree, starts from the root node and swaps its value if its value is less than the value of the child node. Use this method to recursively return the subtree. Then, for all non-leaf nodes of the heap, we invoke the previously described function from the bottom up to get a tree that is larger than its child nodes for each node (non-leaf node). (In fact, this is the process of building the largest heap) after the completion, the list of the head and tail elements of the order, so that the last one of the list is the largest number, and then in the list of 0 to n-1 part of the above to establish the maximum heap of the process. Finally get a list of heap sorting finishes. Here is the source code:

Class Heap_sort (object): Def _left (self, i): Return 2*i+1 def _right (self, i): Return 2*i+2 def _parent (self, i): if I%2==1:return int (I/2) Else:return i/2-1 def _max_heapify (self, alist, I, Heap_size=none): Lengt h = Len (alist) if heap_size is none:heap_size = length L = self._left (i) r = self._right (i) if l < he Ap_size and Alist[l] > Alist[i]: largest = l Else:largest = i if r < heap_size and Alist[r] > al Ist[largest]: largest = r if Largest!=i:alist[i], alist[largest] = Alist[largest], Alist[i] Self._max_h Eapify (alist, Largest, heap_size) def _build_max_heap (self, alist): Roop_end = Int. (len (alist)/2) for I in range (0, Roop_end) [:: -1]: self._max_heapify (Alist, i) def __call__ (self, sort_list): Self._build_max_heap (sort_list) he Ap_size = Len (sort_list) for I in range (1, Len (sort_list)) [:: -1]: sort_list[0], sort_list[i] = Sort_list[i], Sort_ List[0] Heap_size-= 1 self._max_heapify (sort_list, 0, heap_size) return sort_list 

The last kind of exchange sorting algorithm to be explained (all of the above algorithms are sort of exchange, because all need to compare the Exchange order by 22) is naturally the classic fast sort.

Let's start with the principle. The first thing to use is the Partition tool function (partition), for a given list (array), we first select the Datum element (here I choose the last Element), by comparing, finally make the position of the element, The new list (running in-place) at the end of this run is all less than the Datum element on the left side of the datum element, and the number on the right is greater than it. Then we use the partitioning function for the list to be sorted, divide the list into the left and right two lists (ideally), and then recursively call the partition function until the length of the subsequence is less than or equal to 1.

Here is the quick sort of source code:

Class Quick_sort (object):  def _partition (self, alist, p, r):    i = p-1    x = alist[r] for    J in range (P, r): 
    if Alist[j] <= x:        i + = 1        alist[i], alist[j] = Alist[j], alist[i]    alist[i+1], alist[r] = Alist[r], alist[i +1]    return i+1  def _quicksort (self, alist, p, r):    if P < r:      q = self._partition (Alist, P, r)      Sel F._quicksort (Alist, p, q-1)      self._quicksort (Alist, q+1, R)  def __call__ (self, sort_list):    self._ Quicksort (sort_list, 0, Len (sort_list)-1)    return sort_list

A careful friend here may find a problem, if the sequence is exactly the order, the entire recursion will reach the maximum recursion depth (the length of the sequence). In practice, when the list length is greater than 1000 (the theoretical value), the program breaks, reporting an error exceeding the maximum recursion depth (maximum recursion depth exceeded). After checking the data we know that Python by default, the maximum recursion depth is 1000 (theoretical value, in fact, only about 995, the size of each system is different). There are two solutions to this problem, 1) reset the maximum recursive depth, set in the following ways:

Import Syssys.setrecursionlimit (99999)

2) The second method is to use a different version of the partition function, called the randomized partition function. Since our selection was the last number of the subsequence, the robustness of the particular case was much worse. Now we randomly select the datum elements from the sub-sequence, which reduces the error rate of the particular case. The new Randomize partition function is as follows:

def _randomized_partition (self, alist, p, r):  i = Random.randint (P, R)  Alist[i], alist[r] = Alist[r], Alist[i]
    return self._partition (Alist, p, R)

The complete Randomize_quick_sort code is as follows (here I directly inherit from the previous Quick_sort Class):

Import Randomclass Randomized_quick_sort (quick_sort): Def _randomized_partition (self, alist, p, r): i = Random.randint (P, R) Alist[i], alist[r] = Alist[r], Alist[i] return self._partition (Alist, P, R) def _quicksort (self, alist, p, R ): if P
   
    

The discussion about quick sorting is not over yet. As we all know, Python is a very elegant language, and the code written by Python is quite concise and very readable. Here's another way of writing a quick line, which can be done in just three lines, but without losing the reading. (Of course, to understand the need for a certain Python basis) code is as follows:

def quick_sort_2 (sort_list):  If Len (sort_list) <=1:    return sort_list  return quick_sort_2 ([Lt for Lt in Sort_list[1:] If LT
 
      
       
  =sort_list[0]])
 
      

How do you understand, this code from "Python Cookbook second Edition", this writing shows the strong expression of the list derivation.

For the comparison sorting algorithm, we know that all possible scenarios can be drawn as a binary tree (decision tree model), for n-length list, the decision tree height is h, the leaf node is the list of the total likelihood of chaos is n!, and we know that this binary tree leaf node will not exceed 2^h, so there are 2^ h>=n! , take the logarithm, can know, h>=logn!, this is approximate to O (Nlogn). This means that the best performance of the comparison sorting algorithm is O (NLGN).

Is there a linear time, an algorithm with an O (n) time complexity? The answer is yes. However, the algorithm is very complex because of the order in the actual application. This is just a discussion of the linear sorting algorithm in some special cases. In the special case, the linear sorting algorithm mainly has the counting sort, the bucket sort and the cardinal sort. Here is simply a count sort.

The counting sort is based on the assumption that the ordered sequence is a positive integer. First, declare a new sequence list2, and the length of the sequence is the maximum number in the sequence to be ordered. Traverse the backlog sequence, set its size to i,list2[i]++ for each number, which corresponds to the number of occurrences of the count size I. Then, to apply for a list, the length is equal to the length of the sequence to be sorted (this is the output sequence, it can be seen that the counting sort is not an in-place sorting algorithm), the reverse traversal of the sequence (the reason is to maintain the stability of the order, and the same size of two number in the post-order position will not be List[list2[i]-1] = i, while list2[i] is reduced by 1 (this is because the size of the number has been output one, so the size should be self-reducing). So, the source code for the sort of count is as follows.

Class Counting_sort (object):  def _counting_sort (self, alist, K):    alist3 = [0 for I in range (k)]    alist2 = [0 fo R i in range (len (alist))] for    J in Alist:      alist3[j] + = 1    for I in range (1, k):      alist3[i] = alist3[i-1] + A List3[i] for    L in Alist[::-1]:      alist2[alist3[l]-1] = l      alist3[l]-= 1    return alist2  def __call__ ( Self, sort_list, K=none):    if K is None:      import heapq      k = heapq.nlargest (1, sort_list) [0] + 1    return SE Lf._counting_sort (Sort_list, K)

A variety of sorting algorithms are introduced (the above code has passed the unit test I wrote), we return to the topic of Python. In fact, Python starts with the earliest version, replacing the built-in sorting algorithm multiple times. Starting with the Qsort routines provided by the C library (this method has quite a few problems), to the point where you start to implement your own algorithm, including the pre-2.3 sample sorting and the binary insert sort mix, and the newest adaptive sorting algorithm, the code is also 800 lines to 1200 lines from the C language, so much more. From these we can know that in the actual production environment, the use of the classic sorting algorithm is impractical, they can only do study research. In practice, the more recommended approach should follow the following two points:

Try to use the sort method of the built-in Python list when sorting is required.
Try to use the built-in dictionary whenever you need to search.
I wrote the test function to compare the built-in sort method to the superiority of the above method. Test sequence length is 5000, each function test 3 times the average, you can get the following test results:

As you can see, Python built-in functions have great advantages. So in practical applications, we should try to use the built-in sort method.

This leads us to another problem. How to determine if there are duplicate elements in a sequence, and if there is a return of true, there is no return false. Some people will say, this is not very simple, directly write two nested iterations, traverse just. The code should be written down like this.

def normal_find_same (alist):  length = Len (alist)  for I in range (length):    for J in range (i+1, length):      If Alist[i] = = Alist[j]:        return True  return False

The cost of this method is very large (the average time complexity is O (n^2), when there is no duplicate element in the list will be the worst case), from previous experience, we can think of, using the built-in sort method extremely fast experience, we can do this: first sort the list, and then iterate over, See if there are duplicate elements. The complete test code includes the following:

Import Timeimport randomdef Record_time (func, alist):  start = Time.time ()  func (alist)  end = Time.time ()  return end-startdef quick_find_same (alist):  alist.sort ()  length = Len (alist) for  I in range (length-1 ):    if alist[i] = = alist[i+1]:      return True  return falseif __name__ = = "__main__":  methods = (normal_find _same, quick_find_same)  alist = Range ()  random.shuffle (alist) for  m in methods:    print ' the Method%s spends%s '% (m.__name__, Record_time (M, alist))

After running my data is that for 5000 lengths, there is no list of duplicate elements, the normal method takes about 1.205 seconds, and the fast lookup method costs only 0.003 seconds. This is an example of how sorting is applied in practice.

  • 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.