Python implementation of eight sorting algorithms

Source: Internet
Author: User

Insert Sort:

The basic operation of inserting a sort is to insert a data into the ordered data that is already sorted, so as to get a new sequential data with a number plus one, the algorithm is suitable for the ordering of a small amount of data, and the time complexity is O (n^2). is a stable sorting method. The insertion algorithm divides the array to be sorted into two parts: the first part contains all the elements of the array, except for the last element (where an array has more space to insert), and the second part contains only that element (that is, the element to be inserted). After the first part is sorted, the last element is inserted into the first part of the sequence.

1 definsert_sort (lists):2Count =len (lists)3      forIinchRange (1, count):4Key =Lists[i]5j = I-16          whileJ >=0:7             ifLISTS[J] >Key:8LISTS[J+1] =Lists[j]9LISTS[J] =KeyTenJ-= 1 One     returnLists

Hill Sort:

Hill sort Shell Sort is one of the insertion sorts. Also known as narrowing incremental sorting, is a more efficient and improved version of the direct insertion sorting algorithm. Hill Sort is a non-stable sorting algorithm. The method is due to DL. The shell was named after it was introduced in 1959. Hill sort is to group records by a certain increment of the subscript, sorting each group using the direct insertion sorting algorithm; As the increments gradually decrease, each group contains more and more keywords, when the increment is reduced to 1 o'clock, the entire file is divided into a group, the algorithm terminates.

defshell_sort (lists):#Hill SortCount =len (lists) step= 2Group= Count/Step whileGroup >0: forIinchRange (0, Group): J= i +Group whileJ <count:k= J-Group Key=Lists[j] whileK >=0:ifLISTS[K] >key:lists[k+ Group] =Lists[k] Lists[k]=Key k-=Group J+=Group Group/=StepreturnLists

Bubble:

It repeatedly visited the sequence to sort, comparing two elements at a time, and swapping them out if they were wrong in the order. The work of the sequence of visits is repeated until no more need to be exchanged, that is, the sequence is sorted.

 1  def   Bubble_sort (lists):  2  count = Len (lists)  3  for  i in   range (0,count):  4  for  J in  Range (i+1,count):  5  if  lists[i] >= Lists[j]:  6      LISTS[I],LISTS[J] = Lists[j],lists[i]  7  return  lists 

Quick Sort

By sorting the sorted data into separate two parts, one part of all data is smaller than the other part of the data, and then the two parts of the data are quickly sorted by this method, the entire sorting process can be recursive, so as to achieve the entire data into an ordered sequence.

1 defquick_sort (lists, left, right):2     #Quick Sort3     ifLeft >=Right :4         returnlists5Key =Lists[left]6Low = Left7High = Right8      whileLeft <Right :9          whileLeft < Right andLists[right] >=Key:TenRight-= 1 OneLists[left] =Lists[right] A          whileLeft < Right andLists[left] <=Key: -Left + = 1 -Lists[right] =Lists[left] theLists[right] =Key -Quick_sort (lists, low, left-1) -Quick_sort (lists, left + 1, High) -     returnlists

Direct Select sort

Basic idea: The 1th trip, in order to sort records R1 ~ R[n] In the selection of the smallest record, it and R1 Exchange, 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 to select the smallest record, and r[ I] exchange, which keeps the ordered sequence growing until all sorts are completed.

1 defselect_sort (lists):2     #Select Sort3Count =len (lists)4      forIinchRange (0, count):5Min =I6          forJinchRange (i + 1, count):7             ifLists[min] >Lists[j]:8Min =J9Lists[min], lists[i] =Lists[i], Lists[min]Ten     returnLists

Heap Sort

Heap sort Heapsort is a sort algorithm which is designed by using the data structure of pile-up tree (heap), which is a sort of selection. The elements of the specified index can be quickly positioned using the features of the array. The heap is divided into Dagen and small Gan, which are completely binary trees. 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 the non-descending order of the array, it is necessary to use the large root heap, because according to the requirements of Dagen, the maximum value must be at the top of the heap.

1 defadjust_heap (lists, I, size):2Lchild = 2 * i + 13Rchild = 2 * i + 24Max =I5     ifI < SIZE/2:6         ifLchild < size andLists[lchild] >Lists[max]:7Max =Lchild8         ifRchild < size andLists[rchild] >Lists[max]:9Max =RchildTen         ifMax! =I: OneLists[max], lists[i] =Lists[i], Lists[max] A adjust_heap (lists, max, size) - #Create Heap - defbuild_heap (lists, size): the      forIinchRange (0, (SIZE/2)) [::-1]: - adjust_heap (lists, I, size) - #Heap Sort - defheap_sort (lists): +Size =len (lists) - build_heap (lists, size) +      forIinchRange (0, size) [::-1]: ALists[0], lists[i] =Lists[i], lists[0] atAdjust_heap (lists, 0, i)

Merge sort

Merge sort is an effective sorting algorithm based on merging operation, which is a very typical application of divide and conquer by divide-and-conquer method. The ordered Subsequence is merged to obtain a fully ordered sequence, i.e., the order of each subsequence is ordered, and then the sequence of sub-sequences is ordered. If two ordered tables are combined into an ordered table, they are called two-way merging.

The merge process is: Compare the size of a[i] and a[j], if A[I]≤A[J], then the first ordered table elements a[i] copied to r[k], and I and K plus 1; otherwise, the second ordered TABLE element A[j] copied to R[k], and the J and K respectively add 1, This loop continues until one of the ordered tables is finished, and then the remaining elements in the other ordered table are copied to the cells in R from subscript K to subscript t. Merging sorting algorithm we usually use recursive implementation, first to sort the interval [s,t] to the midpoint of the two points, then the left sub-range, then the right sub-range is sorted, and finally the left and right intervals with a merge operation into an orderly interval [s,t].

1 defmerge (left, right):2I, j =0, 03result = []4      whileI < Len (left) andJ <Len (right):5         ifLeft[i] <=Right[j]:6 result.append (Left[i])7i + = 18         Else:9 result.append (Right[j])TenJ + = 1 OneResult + =Left[i:] AResult + =Right[j:] -     returnresult - defmerge_sort (lists): the     #Merge Sort -     ifLen (lists) <= 1: -         returnlists -num = Len (lists)/2 +left =Merge_sort (Lists[:num]) -right =Merge_sort (lists[num:]) +     returnMerge (left, right)

Base sort

Cardinal sort Radix sort belongs to "distributive sort" distribution sort, also known as "bucket method" bucket sort or bin sort, as the name implies, it is through the key value of the part of the information, will be sorted by the elements assigned to some "barrels", in order to achieve the role of sorting, The Cardinal sort method is a sort of stability, its time complexity is O (Nlog (r) m), where R is the base to take, and M is the number of heaps, at some point, the cardinality ranking method is more efficient than other stability sequencing methods.

1 ImportMath2 defRadix_sort (lists, radix=10):3K =Int (Math.ceil (Math.log (max (lists), Radix ))4bucket = [[] forIinchrange (radix)]5      forIinchRange (1, k+1):6          forJinchlists:7bucket[j/(radix** (i-1))% (radix**i)]. Append (j)8         dellists[:]9          forZinchBuckets:TenLists + =Z One             delz[:] A     returnLists

Python implementation of eight sorting algorithms

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.