In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
Record several examples of python algorithm analysis, I believe that many inexperienced people do not know what to do, so this paper summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.
(1) insert sort
Inserts the number of in-situ sort input, which the algorithm rearranges in array A.
At most, only constant numbers are stored outside the array at any one time.
The insertion sort is sort in place, basically without external space.
Starting with the second element, iterate through the entire array in turn.
Among them, the first half is an ordered array and the second half is an unordered array to be sorted.
Each element is compared from back to front until it finds its place.
Insert sort is a stable sort.
Def insert_sort (list1):
For j in range (1jinlen (list1)): # traverses from the second element and places the elements in the specified location in turn
Key = list1 [j] # record the current value
I = j-1 # compare the current values in reverse order from before the current position
While I > = 0 and list1 [I] > key:# if the current value is less than the previous value, the current value is in front of the previous value
List1 [iTun1] = list1 [I] # moves the elements larger than the current value one bit in turn, leaving a place for the current value
I-= 1
List1 [iTun1] = key # inserts the current value after the first value that is less than it
Return list1
If _ name__ = = "_ _ main__":
List1 = [380, 22, 64, 75, 327, 98]
List2 = ["wang", "zhe", "tian", "jin", "da", "xue"]
Ordered_list1 = insert_sort (list1)
Ordered_list2 = insert_sort (list2)
Print (ordered_list1) # [2, 3, 4, 5, 6, 7]
Print (ordered_list2) # ['da']
(2) Bubble sorting
Bubble sort the number of in-situ sort input that the algorithm rearranges in array A.
At most, only constant numbers are stored outside the array at any one time.
Bubble sorting is sort in place, basically without external space.
The bubble sort loops the array in turn, and each loop compares two elements from front to back, so that the latter element is always larger than the previous one.
Therefore, each loop ensures that the largest element in the currently unsorted list is placed at the end of the list.
That is, after each cycle, the length of the unsorted list can be reduced by 1.
Repeat until there is only one element left in the list.
Bubble sorting is a stable sort.
The Python implementation code is as follows:
#-*-coding: utf-8-*-
Def bubbleSort (bubbleList):
ListLength = len (bubbleList) # calculate the length of the sorted list
While listLength > 0:
For i in range (listLength-1):
If bubbleList [I] > bubbleList [iTun1]:
Temp = bubbleList [iTun1]
BubbleList [iTun1] = bubbleList [I]
BubbleList [I] = temp # Exchange the values of bubbleList [I] and bubbleList [iTunes 1]
ListLength-= 1 # after each round of sorting, the last element is already the largest. Therefore, only one element in front of the row is needed.
Return bubbleList
If _ _ name__ = ='_ _ main__':
List1 = [3, 2, 4, 6, 7, 5]
List2 = ["wang", "zhe", "tian", "jin", "da", "xue"]
Ordered_list1 = bubbleSort (list1)
Ordered_list2 = bubbleSort (list2)
Print (ordered_list1) # [2,3,4,5,6,7]
Print (ordered_list2) # ['da',' jin', 'tian',' wang', 'xue',' zhe']
(3)
Merge sorting (MERGE-SORT) is an effective sorting algorithm based on merge operation, which is a very typical application of divide-and-conquer (Divide and Conquer).
The ordered subsequences are merged to get a completely ordered sequence, that is, each subsequence is ordered first, and then the subsequence segments are ordered.
Merge sorting is achieved through recursion and merging.
That is, first, a list is divided into two word lists, and the word list is 1 in length. Then merge in turn to make the synthetic list orderly.
The time complexity of merge sorting is nlogn. The space complexity is n.
The merge sort is a stable sort.
The implementation code of Python is as follows:
#-*-coding: utf-8-*-
Def mergeSort (lists):
If len (lists) = j: # if the start point and the end point coincide or after the end point, no further sorting is required
Return L
Key = L [I] # Select the starting element as the element to be compared
While i
< j: #当起点与终点尚未重合时 while i < j and L[j] >= key: # find the location of the first element less than key
J-= 1
L [I] = L [j] # put the first value less than the key element into the position of the key element
While i
< j and L[i] = A[i]。 在数组的非降序排序中,需要使用的就是大根堆,因为根据大根堆的要求可知,最大的值一定在堆顶。 堆排序首先将待排序的数组存入堆中,并将堆构造为最大/最小堆。再依次从堆中取出堆顶元素,从而得到有序数组。 构造堆时,所用的方法为从最底层有子节点的节点开始依次向上处理。 取出顶元素恢复堆时则是先将末尾元素与顶元素交换位置,在对顶元素进行下沉处理即可。 堆排序是不稳定排序。即相同的元素再经过堆排序后,其先后位置可能发生变化。 堆排序的时间复杂度为N*logN。 Python的代码实现如下: [python] view plain copy # -*- coding: utf-8 -*- #用列表表示一个堆,其中列表中索引为0的位置为空。从索引1开始存放元素。 def parent(i): #在堆中,某个节点的父节点为其索引值整除2。例如索引为4的父节点的索引为2。索引为9的父节点的索引为4。 return i/2 def left(i): #某个节点的左子节点的索引为i*2 return i*2 def right(i): #某个节点的右子节点的索引为i*2+1 return i*2+1 class Heap: #堆的数据结构类 def __init__(self, heapList=[None]): #对堆进行初始化。没有给堆初始列表时,初始化为仅包含一个None元素的列表。 self.heapList = [None] + heapList #有初始化列表时,堆列表为初始化列表前插入None元素 def max_heapfy(self, i): #表明对i节点进行最大堆恢复 if (i*2) >Self.length-1: # when the element does not have child nodes
MaxIndex = I
Elif (iSuppli 2 nodes 1) > self.length-1: # when the element has only the left node
MaxIndex = left (I)
Elif self.heapList [left (I)] > self.heapList [right (I)]: # when the element has both left and right nodes, and the value of the left node is greater than that of the right node
MaxIndex = left (I)
Else: # when the element has both left and right nodes, and the value of the left node is less than that of the right node
MaxIndex = right (I)
If self.heapList [i]
< self.heapList[maxIndex]: #当其子节点值大于其节点值时: self.heapList[i], self.heapList[maxIndex] = self.heapList[maxIndex], self.heapList[i] #交换其子节点的值和其值 self.max_heapfy(maxIndex) #并对其子节点进行最大堆化 def build_max_heap(self): #构建最大堆 self.length = len(self.heapList) #计算堆的大小(包含第一个空元素) for i in range(self.length/2, 0, -1): #从包含子节点的节点开始依次向上遍历 self.max_heapfy(i) def insert(self, k): #向堆内插入元素 self.length += 1 #堆的规模加1 self.heapList.append(float("-inf")) #向堆内插入一个负无穷的数 self.increase_key(self.length, k) #增加元素 def maxinum(self): #查询堆内最大元素,即为索引为1的元素值。 return self.heapList[1] def extract_max(self): #弹出堆内最大元素。 maxValue = self.heapList[1] #取得最大元素值 self.heapList[1] = self.heapList[self.length] #将末尾元素移至堆头 del self.heapList[self.length] #删除末尾元素 self.length -= 1 #将堆的规模减1 self.max_heapfy(1) #对堆顶元素最大堆化 return maxValue def increase_key(self, x, k): #增加元素 self.heapList[x] = k #将新增的负无穷位置赋予插入值 while x >1 and self.heapList [parent (x)] < self.heapList [x]: # when the element index is greater than 1 and its value is greater than its parent node value
Self.heapList [parent (x)], self.heapList [x] = self.heapList [x], self.heapList [parent (x)]
# Exchange its value with the value of its parent node
X = parent (x) # continue to judge its parent node
Def show (self): # presentation heap
Print "the length of queue is", self.length-1
Print "the heapList is", self.heapList [1:]
Def heapSort (unsortedList):
Heap = Heap (unsortedList) # convert a disordered list to a heap
Heap.build_max_heap () # builds the heap to the maximum heap
Print heap.heapList
Print "* heap has been build up*"
For i in range (len (unsortedList), 1,-1):
Heap.heapList [I], heap.heapList [1] = heap.heapList [1], heap.heapList [I] # swaps the end node with the root node
After the # exchange is complete, the node in the I position is the largest element in the current heap. That is, the elements of the I index obtained in each loop are ordered lists.
Heap.length-= 1 # the size of the unsorted heap is reduced by 1
Heap.max_heapfy (1) # at this time, the root node does not meet the requirements of the maximum heap, and the heap needs to be restored to the maximum heap.
Return heap.heapList [1:]
If _ _ name__ = ='_ _ main__':
List1 = [3, 2, 4, 6, 7, 5, 1, 8, 10, 9]
List2 = ["wang", "zhe", "tian", "jin", "da", "xue"]
Ordered_list1 = heapSort (list1)
Ordered_list2 = heapSort (list2)
Print ordered_list1 # [2, 3, 4, 5, 6, 7]
Print ordered_list2 # ['da',' jin', 'tian',' wang', 'xue',' zhe']
After reading the above, have you mastered the method of recording the example analysis of several python algorithms? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 263
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.