Although Python has a lot of advanced modules, but also comes with a battery programming language, but to be a qualified programmer, the basic algorithm still need to master, this article mainly introduces some sort of list algorithm
Recursion is a core concept in the algorithm, there are three characteristics, 1 calls itself 2 has an end condition 3 code size gradually reduced
Example: Only two of the following four functions are recursive
Func3 and Func4 But the output is different, such as the FUNC3 (5) output is 5,4,3,2,1FUNC4 (5) output as 1,2,3,4,5, there is a recursive hierarchy inside.
Two concepts: complexity of time and space complexity
Time complexity: Used to express the speed of the algorithm execution time, with O. Commonly used are: O (logn) with a few cycles of O (n several sides) in half
Spatial complexity: A formula used to evaluate the size of an algorithm's memory, typically using space-time
E.g List lookup: Find the specified element from the list
Input: list, find element
Output: element subscript or no element found
Version 1 Sequential lookup: Starts with the first element in the list, searches sequentially until it is found, and the complexity is O (n)
Version 22 search: From the ordered list, the unknown origin value is compared with the median value, and is searched in half, with the complexity O (LOGN)
The code is as follows:
List = [1,2,3,4,5,6,7,8,9]element= 7deford_sear (list,element): forIinchRange (0,len (list)):ifList[i] = =element:Print('List[{0}]={1}'. Format (i,element))returnIElse: Print('Not found')defbin_sear (list,element): Low=0 High=len (list)-1 whilelow<=High:mid= (Low+high)//2ifelement = =List[mid]:Print('List[{0}]={1}'. Format (mid,element))returnMidelifElement >List[mid]: Low=mid +1Else: High=mid-1returnNonei=Bin_sear (list,element) J= Ord_sear (list,element)
Binary search is better than sequential lookups in terms of time complexity, but there are more demanding conditions where the list must be ordered. The following describes the list ordering:
List sorting is one of the most basic methods in programming, the application is very extensive, such as the major music, reading, film, application list, etc., although Python provides us with a lot of sorting functions, but we sort of as the algorithm of the practice is good.
The first introduction is the simplest of three sort methods: 1 bubble Sort 2 Select sort 3 Insert Sort
Bubble sort: Each adjacent two in the list is swapped if the order is not the size we expect. Time complexity O (n^2)
defBubble (list): high= Len (list)-1#指set a maximum position whileHigh>0: forIinchRange (0,high):ifLIST[I]>LIST[I+1]:#if it's bigger than the next one ,LIST[I],LIST[I+1] = List[i+1],list[i]#Swap LocationHigh-=1#The maximum bit minus 1 returnList#Return to listPrint(Bubble (list))
Optimize:
List = [3,1,5,7,8,6,2,0,4,9]defBubble (list): high= Len (list)-1#set a maximum position forJinchRange (high,0,-1): Exchange= False#the flag of the interchange, if ordered in advance can end before the full traversal forIinchRange (0,j):ifLIST[I]>LIST[I+1]:#if it's bigger than the next one ,LIST[I],LIST[I+1] = List[i+1],list[i]#Swap LocationExchange = True#Set Interchange Flags ifExchange = =False:returnList#return list #返回列表Print(Bubble (list))
Select sort: A trip through the selection of the smallest number in the first place, and then the next traversal until the last element. The complexity remains O (n^2)
list = [3, 1, 5, 7, 8, 6, 2, 0, 4, 9 def
Choice (list):
for I in Range (0,len (list) -1 = i for J in ran GE (I+1,len (list) -1 if LIST[MIN_LOC]&G T;LIST[J]: # min traversal comparison Min_loc =
J List[i],list[min_loc]
= List[min_loc],list[i]
return list print (Choice (list))
Insert Sort: Divides the list into ordered and unordered areas, the first ordered area has only one element, and each time you select an element from the unordered area to be inserted into the ordered area by size
List = [3,1,5,7,8,6,2,0,4,9]defCut (list): forIinchRange (1,len (list)-1): Temp=List[i] forJinchRange (i-1,-1,-1):#start traversing from the maximum of the ordered zone ifList[j]>temp:#if the value to be inserted is less than the value of the ordered areaLIST[J+1] = List[j]#move one back .LIST[J] = Temp#put temp in . returnListPrint(Cut (list))
These three sorting methods have a time complexity of O (n^2) and are less efficient, so here are a few more efficient sorting methods
1 Quick sort: The fastest and fastest sort in a good-to-write sort is best written. Steps for 1 extract 2 or so separate 3 recursive calls
List = [3,1,5,7,8,6,2,0,4,9]left=0right= Len (list)-1defpartition (left,right,list): Temp=List[left] whileLeft <Right : whileLeft<right andList[right]>temp:#when the right value is large, the value does not moveRight-=1List[left]=list[right]#otherwise move to the left whileLeft<right andlist[left]<Temp:left+=1List[right]=List[left] List[left]=TempreturnLeft#return leftright All can, the value is the samedefQuick_sort (left,right,list):ifLeft<right:#Iterative interruptsMID = partition (Left,right,list)#Get Middle PositionQuick_sort (Left,mid-1,list)#Small sequence further iterationsQuick_sort (Mid+1,right,list)#large sequence further iterations returnList#Return to listPrint(Quick_sort (Left,right,list))
The time complexity of the Clippers is best when O (Nlogn) is the worst case O (n^2)
The following is a description of heap sequencing. Simply mention the concept of the tree before describing the heap ordering:
A tree is a data structure (such as a directory), a tree is a kind of recursive information structures, related concepts have root nodes, leaf nodes, tree depth (height), the degree of the tree (the most nodes), children node/parent node, subtree, etc.
The most special in the tree is the binary tree (the tree with a degree of not more than 2), the binary tree is divided into two cross-tree and complete binary tree, see:
Binary tree Storage methods are: 1 Chain storage 2 sequential storage (list)
The relationship between the parent node and the left child node number is I--2i+1, and the right child is I--and 2i+2 the last parent node is (LEN (list)//2-1) thus can find the child by the father or vice versa.
Know the tree can be said heap, heap divided into Dagen and small Gan, respectively, the definition is: A complete binary tree, to meet any node is larger or smaller than its child node.
The process of heap sequencing:
-
- Build heap
- Get the top element of the heap, for the maximum value
- Remove the top of the heap, place the last element on top of the heap, and then make a heap sort (iteration)
- The second top of the heap is the second most value
- Repeat 3,4 until heap is empty
The code is:
List = [3, 1, 5, 7, 8, 6, 2, 0, 4, 9]defSift (low, High, list):#Low is the parent node, and high is the last node numberi =Low J= 2 * i + 1#child node Locationtemp = List[i]#Storing temporary variables whileJ <= High:#traverse a child node to the last ifJ < High andLIST[J] < List[j + 1]:#If the second child node is greater than the first child nodeJ + = 1ifTemp < LIST[J]:#If the parent node is smaller than the child node's valueList[i] = List[j]#Parent-Child swap locationi = j#make the next numberj = 2 * i + 1Else: Break #Traversal Complete ExitList[i] = Temp#Returning temporary variablesdefHeap_sort (list): N=len (list) forIinchRange (n//2-1,-1,-1):#start with the last parent nodeSift (i, n-1, list)#Complete Heap Sorting forIinchRange (n-1,-1,-1):#Start draining dataList[0], list[i] = List[i], list[0]#SwapSift (0, i-1, list)#make a new round of heap sorting returnListPrint(Heap_sort (list))
Merge sort: Suppose that the list can be divided into two ordered sub-lists, and how to combine the two sub-lists into an ordered list becomes a merge.
Principles such as:
The code is as follows:
defMerg (low,high,mid,list): I=Low J= Mid +1list_temp= []#define a temporary list whileI <=mid andJ <=High :ifLIST[I]<=LIST[J]:#Compare the size of ordered sub-list elements, respectivelyList_temp.append (List[i])#Add to the temp listI +=1Else: List_temp.append (List[j]) J+=1 whileI <=mid:list_temp.append (list[i]) I+=1 whileJ <=high:list_temp.append (List[j]) J+=1List[low:high+1]=list_temp#assigns the list of completed orders to the corresponding location in the original listdefMerge_sort (low,high,list):ifLow <High:mid= (Low+high)//2#two-part methodMerge_sort (Low,mid,list) Merge_sort (Mid+1,high,list)#recursive Invocation,Merg (low,high,mid,list)returnlistlist= [3,1,5,7,8,6,2,0,4,9]Print(Merge_sort (0,len (list) -1,list))
Version2 Less code:
defmergesort (lists):ifLen (lists) <= 1: returnLists num= Int (len (lists)/2) Left=mergesort (Lists[:num]) right=mergesort (lists[num:])returnMerge (left, right)defMerge (left, right): R, L=0, 0 result= [] whileL < Len (left) andR <Len (right):ifLEFT[L] <Right[r]: Result.append (Left[l]) L+ = 1Else: Result.append (Right[r]) R+ = 1result+=right[r:] Result+=Left[l:]returnresultPrint(MergeSort (list))
Summary of the quick-row, heap-row, Merge:
- The complexity of Time is O (NLOGN)
- Quick Arrange < Merge < Heap (general)
- The disadvantage of the fast line: the extreme is inefficient, can go to O (n^2), merging is the need for additional overhead, the heap is relatively slow in the sorting algorithm
Python common algorithms