Summary of sorting algorithms

Source: Internet
Author: User
Tags for in range

Review the sorting algorithm once again, summarize and record

First look at two different recursion
def func3 (x):     if x>0:        Print(x)        func3 (x-1)def  Func4 (x):     if x>0:        func4 (x-1)        print(x) func3 (5) Func4 (5)

FUNC3 (5) Output 5,4,3,2,1

FUNC4 (5) Output 1,2,3,4,5

To understand the differences between the two recursion, Func3 is the time to go into the hand to print, so it is 5,4,3,2,1. Func4 is the time to print out the recursion,

Two-insert Sort
def Insert_sort (LI):      for  in range (1, Len (LI)):        = Li[i]        = i-1 while and         li[j] > tmp:             + 1] = Li[j]            = j-1        + 1] = tmp

Insert a record into the sorted ordered table to get a new, sequential table with a 1 increase in the number of records. That is, the 1th record of the sequence is considered to be an ordered subsequence, and then inserted from the 2nd record one after the other until the entire sequence is ordered. If you encounter an equal to the insertion element, the insertion element places the element you want to insert behind the equal element. So, the order of the equal elements is not changed, the order from the original unordered sequence is the order of the sequence, so the insertion sort is stable.

Efficiency:

Complexity of Time: O (n^2)

Three-choice sort
def Select_sort (LST):      for  in range (len (LST)-1):        = i        for in range (i + 1, Len (LST)): c12/>if lst[j] < lst[min]:                = J        = Lst[min], lst[i]

Basic idea: In the group of numbers to be sorted, select the minimum (or maximum) number to exchange with the number of the 1th position, and then in the remaining number, find the minimum (or maximum) number of the 2nd position to exchange, and so on, until the first N-1 element (the penultimate number) and the nth element (the last number) to compare.

Operation Method:

First trip, from N records to find the minimum key code record and the first record exchange;

Second, the second record from the beginning of the n-1 record to select the minimum key code record and the second record exchange;

And so on .....

On the first trip, the smallest record of the key code is selected from the N-i+1 record starting with the first I record, and the first record is exchanged until the entire sequence is ordered by key code.

Efficiency:

Complexity of Time: O (n^2)

Four bubble sort
defBubble_sort (LST): forIinchRange (len (LST)-1): Exchange=False forJinchRange (len (LST)-i-1):            ifLST[J] > lst[j + 1]: lst[j], lst[j+ 1] = lst[j + 1], Lst[j] Exchange=True#If you find a trip without any exchange, the instructions are lined up, and the rest will not be done.        if  notExchange: Break

Basic idea: In order to sort a group of numbers, the current is not yet ranked in the range of all the number, the top-down to the adjacent two numbers in turn to compare and adjust, so that the larger number to sink, smaller upward. That is, each time a comparison of two adjacent numbers finds that they are in the opposite order of order, they are interchanged. The optimization is also done here.

Efficiency:

Complexity of Time: O (n^2)

Five Quick sort first way
defInner_sort (LST, left, right): Tem=Lst[left] whileLeft <Right : whileLeft < Right andLst[right] >=Tem:right-= 1Lst[left]=Lst[right] whileLeft < Right andLst[left] <=Tem:left+ = 1Lst[right]=Lst[left] Lst[left]=temreturn Leftdefquick_sort_x (LST, left, right): whileLeft <Right:mid=Inner_sort (LST, left, right) quick_sort_x (LST, left, mid-1) quick_sort_x (LST, Mid+ 1, right)defQuick_sort (LST): quick_sort_x (LST, 0, Len (LST)-1)

The second way
defQuick_sort (LST):defqsort (LST, begin, end):ifBegin >=End:returnPivot=Lst[begin] I=begin forJinchRange (begin + 1, end + 1):            ifLST[J] <pivot:i+ = 1Lst[i], Lst[j]=Lst[j], Lst[i] lst[begin], Lst[i]=Lst[i], Lst[begin] qsort (LST, begin, I-1) qsort (LST, I+ 1, end) qsort (LST, 0, Len (LST)-1)

Basic idea:

1) Select a datum element, usually select the first element or the last element,

2) Divide the records to be sorted into separate two parts by a single pass, and some of the recorded element values are smaller than the datum element values. The element value of another part of the record is larger than the base value.

3) At this point the datum element is in the correct position after it is sorted

4) Then proceed to sort the two parts of the record in the same way until the entire sequence is ordered.

Examples of quick sorting:

Efficiency:

Fast sorting is generally considered to be the best average performance in a sorting method of the same order of magnitude (O (nlog2n)). However, if the initial sequence is ordered or basically ordered by key code, the fast sort is degenerate to bubble sort instead. In order to improve it, we usually select the Datum record by "Three take Chinese Method", and adjust the center of the two endpoint of the sorting interval and the midpoint three record key code to the pivot record. Fast sorting is an unstable sort method.

Six merge sort
defOne_merge_sort (LST, begin, Mid, end): left=Begin Right= Mid + 1#the mid here is the subscript for the element at the end of the first half, so be sure to understand that because it's left <= mid below,Temp_list = []     whileLeft <= mid andRight <=End:ifLst[left] <Lst[right]: Temp_list.append (Lst[left]) left+ = 1Else: Temp_list.append (Lst[right]) right+ = 1 whileLeft <=mid:temp_list.append (Lst[left]) left+ = 1 whileRight <=end:temp_list.append (Lst[right]) right+ = 1#Note that this must not be written in lst[:]=temp_list because in each recursion, you can only replace the part that is already in place, instead of replacing it allLst[begin:end + 1] =temp_listdef_merge_sort (LST, begin, end):ifBegin <End:mid= (begin + END)//2_merge_sort (LST, begin, mid) _merge_sort (LST, Mid+ 1, end) One_merge_sort (LST, begin, Mid, end)defMerge_sort (LST): _merge_sort (LST, 0, Len (LST)-1)

Merge sort is an efficient sorting algorithm based on the merging operation. This algorithm is a very typical application of the partition method (Divide and Conquer). First consider how to combine the two ordered series. This is very simple, as long as the first number from the comparison of two series, who is the first to take who, and then compare, if there are several columns empty, then directly the other sequence of data to be taken out in turn. It can be seen that the efficiency of the combined ordered series is relatively high and can reach O (n).

Solve the above merge ordered series, and then look at the merger sort, the basic idea is to divide the array into two groups, a, if the two groups of data are ordered, then it is convenient to the two groups of data to sort. How do you get the data in the two groups in order? A and B groups can be divided into two groups respectively. And so on, when the group has only one data, it can be thought that the group has reached an orderly, and then merge the adjacent two groups. This is done by first recursive decomposition of the series, and then merging the sequence to complete the merge sort.

Seven-heap sort
defShift (data, Low, hight):"""assuming that the rest of the heap is already a one-time adjustment except for the stack vertices"""I=Low J= 2 * i + 1tem=Data[i] whileJ <=hight:ifJ + 1 <= hight andData[j + 1] >Data[j]: J+ = 1ifDATA[J] >Tem:data[i]=Data[j] I=J J= 2 * i + 1Else:             BreakData[i]=temdefheap_sort (data): N=len (data)#this for loop is for building heaps .     forIinchRange (n//2-1,-1, 1): Shift (data, I, n-1)#Now that the heap is built, the next step is to take the number from the heap     forIinchRange (n-1,-1,-1): Data[i], data[0]=data[0], Data[i] Shift (data, 0, I-1)

Heap sorting is a sort of tree selection, which is an effective improvement on direct selection sorting.

Basic idea: The heap is defined as follows: A sequence with n elements (k1,k2,..., kn), which is called a heap when the parent node is either greater than (or less than) a child node. As can be seen from the definition of a heap, the top element of the heap (that is, the first element) must be the smallest item (the small top heap). If a heap is stored in a one-dimensional array, the heap corresponds to a complete binary tree, and the values of all non-leaf nodes are not greater than (or not less than) the values of their children, and the value of the root node (the top element of the heap) is the smallest (or largest). Such as:

(a) Large top pile sequence: (96, 83,27,38,11,09)

(b) Small top heap sequence: (12,36,24,85,47,30,53,91)

Initially, the sequence of n numbers to be sorted is considered to be a sequential stored two-fork tree (one-dimensional array storage binary tree), adjust their storage order, make it a heap, the top element of the heap output, to get the smallest (or largest) elements of n elements, then the number of root nodes of the heap minimum (or maximum). Then the front (n-1) element is re-adjusted to make it a heap, the output heap top element, to get n elements of the minor (or minor) element. And so on, until there are only two nodes of the heap, and exchange them, and finally get an ordered sequence of n nodes. Call this process a heap sort.

The implementation method is as follows:

    1. First assume a heap (not called a heap, because his vertices do not meet the conditions of the heap, this is called), this heap in addition to the vertex, the other nodes are a complete binary tree heap, the heap is adjusted to make it a real full binary tree heap, the process is the shift function,
    2. From the last moment, the parent node of the child node begins the loop, and the parent node and all of his child nodes can be viewed as 1. Execute the SHIFT function in the loop, and when the loop is finished, the heap is built,
    3. From the top of the heap, the method is as follows, 1. First take the number of the top of the heap, take the last number, take the last number up, the heap becomes 1) in the form of the heap, and perform a 1) operation, and then take the number on the line, in order to simplify the understanding, you can take the number of the top of the heap into an empty But here in order not to open the extra memory to put out the number of the last one in the original list, the next cycle, the sequence of the n-1, as a heap loop.

The time complexity is also: O (NLOGN)

Eight summary

In fact, various algorithms, especially the latter three more complex algorithms, to use the language to describe the process of these algorithms clearly, really a bit difficult, the only way to master these algorithms is to review more, write several times

Summary of sorting algorithms

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.