Data structure-sorting algorithm principle and Python implementation

Source: Internet
Author: User

Sorting algorithm Overview

Insert Sort

The basic idea is to tell a record to be sorted each time, and insert it into the sequence of the previous shot by its keyword size until it's all done.

Direct Insert Sort

The speaking element L (i) is inserted into the ordered sequence l[1,..., I-1], performing the following actions: 1. Find the insertion position of L (i) in l[1,..., I-1] K. 2. Move all the elements in L[k,..., i-1] back one bit. 3. Copy L (i) to L (k)

def Insertsort (Array_a, N):      for  in range (1, N):        = Array_a[i]        = i-1 while and         J >= 0:             + 1] = Array_a[j]  #  If it is less than its predecessor, look for the insertion position and move backwards from the back.             J-=        1 + 1] =    tempreturn array_a
Hill sort

The essence of hill Sort is grouping insert sort. Basic idea: 1. Take a step D1 (typically N/2) that is less than N, and divide the table into D1 groups, each of which has an element interval of D1. 2. Use direct insert sorting within each group. 3. Select the second step, typically d1/2, to repeat the process until the step is 1.

The strict meaning of the hill sort:

defShellsort (Array_a, N): DK= N/2 whileDK >= 1:         forIinchxrange (0, DK): forJinchRange (i +DK, N, dk): Temp=Array_a[j] k= J-DK whileTemp < Array_a[k] andK >=0:array_a[k+ DK] = Array_a[k]#if it is smaller than its predecessor, look for the insertion position and move backwards from the back. K-=DK array_a[k+ DK] =Temp DK= DK/2returnArray_a

In fact, each element and interval DK Multiples of the precursor comparison, do insert sort, simplified version:

 def   ShellSort2 (Array_a, N): DK  = N/2 while  dk >= 1:  for  i in   range (DK, n): Temp  = Array_a[i] K  = i- DK  
   
    while  temp < array_a[k] 
    and  k >=
     0:array_a[k  + DK] = array_a[k] 
    #  
     If it is smaller than its predecessor, look for the insertion position and move backwards from the back.  k-=
     DK array_a[k  + DK] =
     temp DK  = dk/2 
    return  array_a 
   
Exchange sort

The interchange swaps the positions of two elements based on the results of the comparison of two elements in a sequence.

Bubble sort
    1. For a table of length n, compare the values of 22 adjacent elements from the back to the next, and then exchange their values in reverse order until the sequence is compared, this is a trip.
    2. The next trip is to reduce a row of elements, and finally n-1 the sequencing to complete.
defBubblesort (Array_a, N): forIinchRange (0, n-1): Flag= 0#Swap Flags         forJinchRange (n-1, I, 1):            ifARRAY_A[J] < Array_a[j-1]: Temp=Array_a[j] Array_a[j]= Array_a[j-1] Array_a[j-1] =Temp Flag= 1ifFlag = =0:returnArray_a#If this trip has not been exchanged, the instructions are orderly and return    returnArray_a
Quick Sort

Quick Sort Basic idea: 1. Select an element in the table to be sorted as pivot, which is used as a baseline to divide the array into two parts that are larger and smaller than the other, at which point the pivot is placed in the final position. 2. Then recursively perform the above procedure for two sub-tables 3. Until each part has only one element or is empty

defQuickSort (array_a, Low, high):ifLow <High:pivotpos=Partition (array_a, Low, high) QuickSort (array_a, Pivotpos+ 1, High) QuickSort (array_a, Low, Pivotpos-1)    returnarray_adefPartition (array_a, Low, high): Pivot=Array_a[low] whileLow <High : whileLow < High andArray_a[high] >=Pivot:high-= 1Array_a[low]= Array_a[high]#element with left shift smaller than pivot         whileLow < High andArray_a[low] <=Pivot:low+ = 1Array_a[high]= Array_a[low]#move the element that is larger to the right than pivotArray_a[low] =PivotreturnLow
Select sort

Basic idea: 1. Initial i=0. 2. I trip in the following n-i+1 elements, select the smallest, as the value of the element I. 3. Until i=n-1 is done.

Simple selection sorting

In line with the thought above, each trip finds the minimum and the first element exchange. Find the minimum element using the traversal method:

def Selectsort (arrau_a, N):      for  in xrange (n-1):        = i        -in range (i + 1, N):              if array_a[j] < array_a[min]:                = J        = Array_a[i]        =  Array_a[min]        = Temp

Heap Sort

Heap sorting is a kind of tree selection sorting method, which uses the relationship between parent and child node in binary tree to select the key maximal (minimum) element of disordered region. Heap definition: A sequence of n keywords is called a heap when and only if it satisfies: 1. L (i) ≤l (2i) and L (i) ≤l (2i+1) or 2. L (i) ≥l (2i) and L (i) ≥l (2i+1) of which 1 are small Gan, 2 is a large root heap.

The key to heap sequencing is to build the initial heap, the direct large heap code

defbuildmaxheap (Array_a, N): forIinchRange (N/2, 0,-1):#from I=[n/2-1]~0, repeatedly adjust the heap. Adjustdown (Array_a, I, n-1)defAdjustdown (array_a, K, N): array_a[0]=Array_a[k] I= 2 *k while(I <= N):#filtering along the sub-nodes of K        ifI <N:ifArray_a[i] < Array_a[i + 1]: I+ = 1#take a larger sub-node .        ifArray_a[0] >Array_a[i]: Break        Else: Array_a[k]= Array_a[i]#Array_a[i] adjusted to the parents. K =I i*= 2Array_a[k]= Array_a[0]#the filtered points are placed in the final position. defheapsort (Array_a, N): Array_a.insert (0, 0)#first Array_a all elements back, rray_a[0] do not store elementsn =Len (array_a) buildmaxheap (array_a, N) forIinchRange (n-1, 1, 1): Temp=Array_a[i] Array_a[i]= Array_a[1] array_a[1] = Temp#places the largest element at the end of the current unordered arrayAdjustdown (array_a, 1, i-1)#tidy up the rest of the i-1. 

Merge sort

A merge sort is a new ordered table that consists of two or more ordered tables. The following is a two-way merge as an example: recursive implementation: 1. First to sort the interval [s,t] to the midpoint of the two points, then the left sub-range is sorted, and then the right sub-interval is sorted, and finally the left and right intervals are merged into an orderly interval [s,t]. 2. Merge two ordered arrays: 1. The size of the array comparison a[i] and a[j]. 1. If a[i]≤a[j], copy the element in the first ordered table A[i] to r[k], and let I and k respectively add 1; 2. Otherwise, copy the elements in the second ordered table A[j] to r[k] and add 1 to J and K respectively. 2. Loop down until one of the ordered tables is finished, and then copy the remaining elements from the other ordered table to the cells in R from subscript K to subscript t.

defMerge (Array_a, Low, Mid, high):#merge Array_a's [Low,... mid] and [mid+1,... High] with their ordered two parts as a new ordered tableb = []     foreachinchArray_a[low:high + 1]: B.append (each)#Save the sequence to B. I, j = Low, Mid + 1#in fact, I,j is the location where the two tables are compared. K =I whileI <= mid andJ <=High :#adds a smaller element to the array array_a.         ifB[i-low] <= b[j-Low ]: Array_a[k]= B[i-Low ] I+ = 1Else: Array_a[k]= B[j-Low ] J+ = 1k+ = 1#If two tables have one that is not instrumented, then copy.      whileI <=Mid:array_a[k]= B[i-Low ] K+ = 1I+ = 1 whileJ <=High:array_a[k]= B[j-Low ] K+ = 1J+ = 1defmergesort (array_a, Low, high):ifLow <High:mid= (low + high)/2#divided into two sub-sequences. MergeSort (Array_a, Low, mid)#recursively sorts the sub-sequences separately. MergeSort (Array_a, Mid + 1, High) Merge (Array_a, Low, Mid, high)#merges the left and right two ordered sub-sequences. 

Base sort

The radix sort is not based on the comparison persona, but uses the idea of multi-keyword ordering, that is, according to the key word size sorting, the highest bit is limited and the lowest bit priority is sorted.

Data structure-sorting algorithm principle and Python implementation

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.