Python Learning (iii) Implementation of eight sorting algorithms (bottom)

Source: Internet
Author: User

In this paper, Python implements the following four kinds of insert sort, cardinal sort, hill sort, bubble sort, high speed sort, direct selection sort, heap sort, merge sort.


Previous: Python Learning (iii) Implementation of eight sorting algorithms (Part One)

1. High-speed sequencing

Descriptive narrative
By sequencing the data to be sorted into separate two parts, one part of the whole data is smaller than the other part of the whole data, and then the two parts of the data by the method of high-speed sorting, the entire sequencing process can be recursive, so as to achieve the entire data into an ordered sequence.


1. First, a number is taken from the series as the base number.


2. The partitioning process, which puts the number of large numbers on its right, is less than or equal to its number to the left.


3. Repeat the above process

Code implementation

 def quick_sort(lists):    ifLists = = []:return[]Else: divide = lists[0] Lesser = Quick_sort ([x forXinchlists[1:]ifX<divide])#链表推导式. The return value is a linked list of elements resulting from an expression after the for or if clauseBigger = Quick_sort ([x forXinchlists[1:]ifX>=divide])returnLesser + [divide] + biggerif__name__=="__main__": Lists = [ +,-3,2,Ten, $,- the, -]PrintQuick_sort (lists)
2. Direct selection of sorting

Descriptive narrative
Basic idea: The 1th trip, in order to sort records R1 ~ R[n] To select the smallest record, it and R1 Exchange. The 2nd trip, in order to sort records R2 ~ R[n] In the selection of the smallest record, it and R2 exchange, and so on, the first trip in order to sort records R[i] ~ r[n) in the selection of the smallest record, and r[i] exchange, so that the orderly sequence continues to grow until all sorts are completed.
Code implementation

 def select_order(lists):Length = Len (lists) forIinchRange0, length): min = i forJinchRange (i+1, length):ifLists[min] > lists[j]: Min = j Lists[min],lists[i] = Lists[i],lists[min]returnListsif__name__ = =' __main__ ': Lists = [ A, -, the,9, -, -]PrintSelect_order (lists)
3. Heap Sequencing

Descriptive narrative
Heap sorting (heapsort) is a sort algorithm designed using data structures such as stacked trees (heaps), which is a sort of selection. The ability to position the elements of the specified index at high speed using the array's characteristics. The heap is divided into Dagen and small Gan. is a completely binary tree.

The Dagen requirement is that the value of each node is not more than the value of its parent node, i.e. A[parent[i]] >= a[i].

In a non-descending sort of array. Need to use is the big root heap, because according to the requirements of Dagen, the maximum value must be at the top of the heap.

Taking advantage of the greatest features of the top elements of a large top heap, the largest elements are constantly removed, and the remaining elements are adjusted to the large top pile. Removing the largest element in turn is the list of the ordered items.
Code implementation

 def build_heap(lists):Count = Len (lists) forIinchRange (count//2-1,-1,-1): Adjust_heap (Lists,i,count) def adjust_heap(lists,i,n):j = i*2+1     whileJ < n:ifj+1< n andlists[j]<lists[j+1]: J + =1        ifLists[i] > Lists[j]: BreakLISTS[I],LISTS[J] = Lists[j],lists[i] I = j J = i*2+1#大顶堆排序 def heap_sort(lists):Count = Len (lists) build_heap (lists)#交换堆顶与最后一个结点, and then adjust the heap     forIinchRange (Count-1,0, -1): lists[0], lists[i] = lists[i], lists[0] Adjust_heap (lists,0IreturnListslists = [-3,1,3,0,9,7]PrintHeap_sort (lists)
4. Merge sort

Descriptive narrative
Merge sort is an effective sorting algorithm based on merging operation, which is a typical application of Divide and conquer by divide-and-conquer method.

Merges an ordered sequence of sub-sequences. Get a completely ordered sequence, that is, the order of each subsequence first. And then order the sub-sequences between segments. If two ordered tables are combined into an ordered table, they are called two-way merging.
The merge sort detail works such as the following (if a sequence has n elements in common):
1. Merge each contiguous two digits of the sequence to form a sequence that includes two elements for each sequence after sorting
2. Merge the above sequence again to form a sequence. Each sequence consists of four elements
3. Repeat step 2. Until all elements are sorted

Code implementation

 def merge_sort(lists):    ifLen (lists) <=1:returnLists left = Merge_sort (Lists[:len (lists)/2] right = Merge_sort (Lists[len (lists)/2: Len (lists)]) result = [] whileLen (left) >0  andLen (right) >0:if(left[0] > right[0]): Result.append (Right.pop (0))Else: Result.append (Left.pop (0))if(Len (left) >0): Result.extend (Merge_sort (left))Else: Result.extend (Merge_sort (right))returnResult def main():Lists = [2, One, -, -, +, -, -]PrintMerge_sort (lists)if__name__=="__main__": Main ()

Python Learning (iii) Implementation of eight sorting algorithms (bottom)

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.