Python Sorting Algorithm and python sorting
I. Bubble Sorting
A two-layer for loop compares the size of the current number with the next bit, for example, small, switching position.
1 def bubble_sort(data):2 for i in range(len(data)-1):3 for j in range(len(data)- i -1):4 if data[j]<data[j + 1]:5 data[j], data[j + 1] = data[j + 1], data[j]
View Code
Ii. Insert sorting
The number of digits after the cyclic ordered series. If the number is greater than the last digit of the ordered series, the two digits are exchanged and compared with the last second digit of the ordered series, and so on.
1 def insect_sort(data):2 for i in range(1, len(data)):3 tmp = data[i]4 j = i - 15 while j<=0 and data[j] > tmp:6 data[j],data[j + 1] = data[j + 1],data[j]7 j -= 18 data[j + 1] = tmp
View Code
3. Select sorting
Find the minimum number for each for loop as the result of this loop.
1 def select_sort(data):2 for i in range(len(data)-1):3 min_num = i4 for j in range(i+1, len(data)):5 if data[j]<data[i]:6 min_num = j7 data[i], data[min_num] = data[min_num], data[i]
View Code
Iv. Fast Release
Select the first number and compare the cycles from the left. For example, if the number is smaller than or equal to the number, place a small number to the first number and start the loop from the right. For example, if the number is greater than, stop the loop, place a large number on the space of the previous loop, so that until left = right, mid is returned for recursion.
1 def quick_sort(data,left,right): 2 if left<right: 3 mid = partition(data,left,right): 4 quick_sort(data,left,mid-1) 5 quick_sort(data,mid+1,right) 6 7 def partition(data,left,right): 8 tmp = data[left] 9 while left < right:10 while left < right and data[right]>=tmp:11 right -= 112 data[left] = data[right]13 while left < right and data[left]<=tmp:14 left += 115 data[right] = data [left]16 data[left] = tmp17 return left
View Code
V. Heap sorting
First, adjust the heap building cycle from the smallest parent node with a child node, then take the number, change the end of the heap to the top of the heap, and then adjust the heap top with the changed position, this loop.
1 def sift (data, low, high): 2 I = low 3 j = 2 * I + 1 4 tmp = data [I] 5 while j <= high: # As long as the last 6 if j View Code