Eight sorting algorithms achieve python

A bubble sort

Bubble sort algorithm operates as follows:

Compare adjacent elements. If the first is greater than the second, the two of them exchanged.
Do the same work for each pair of adjacent elements, from the beginning to the end of the first to the last pair. Once this is done, the last element is the biggest number.
Repeat these steps for all elements, except the last one.
Continued to repeat the above steps for each time fewer and fewer elements, a pair of numbers until there is no need to compare.
Above excerpt from Wikipedia

Code:

def bubble_sort(numberlist):
length = len(numberlist)
for i in range(length):
for j in range(1, length - i):
if numberlist[j - 1] > numberlist[j]:
numberlist[j], numberlist[j - 1] = numberlist[j - 1], numberlist[j]
return numberlist
二、选择排序

Selection Sort (Selection sort) is a straightforward sorting algorithm. It works as follows. First, find the smallest sequence of unsorted (large) element, the starting position is stored in the sorted sequence, and then continue to find the minimum (large) element from the remaining elements of unsorted and sorted into the end of the sequence. And so on, until all the elements are sorted.

Above excerpt from Wikipedia

Code:

def findSmallest (arr): # to find out the smallest element in the array, returns the index of the smallest element.
ARR = Smallest [0]
smallest_index = 0
for I in Range (. 1, len (ARR)):
IF Smallest> ARR [I]:
Smallest ARR = [I]
smallest_index = I
return smallest_index

def selectSort(arr):
newArr = []
while arr:
smallest = findSmallest(arr)
newArr.append(arr.pop(smallest))
return newArr

Third, insertion sort

Proceed as follows

Starting with the first element, which can be considered to have been sorted
fetches the next element from the forward scan in the sequence of elements has been ordered in
if the element (sorted) is greater than the new element, the element to the next position
repeat step 3 until you find the position of the sorted elements less than or equal to the new element
after the element is inserted into the new position
repeat steps 2-5
above excerpt from Wikipedia

Code

def insert_sort(data):
for k in range(1, len(data)):
cur = data[k]
j = k
while j > 0 and data[j - 1] > cur:
data[j] = data[j - 1]
j -= 1
data[j] = cur
return data
四、希尔排序

Shell sort through all of the elements to be compared is divided into several areas to improve performance of insertion sort. This allows a one-time element can be a big step forward towards the final position. The algorithm then more and then take small steps to sort, the last step is an ordinary insertion sort algorithm, but to this step, you need to sort the data had already been booked almost a good (this time insertion sort faster).

Above excerpt from Wikipedia

Code:

def shell_sort(numberlist):
length = len(numberlist)
gap = length // 2
while gap > 0:
for i in range(gap, length):
temp = numberlist[i]
j = i
while j >= gap and numberlist[j - gap] > temp:
numberlist[j] = numberlist[j - gap]
j -= gap
numberlist[j] = temp
gap = gap // 2
return numberlist
五、归并排序

Principle is as follows (assuming consensus sequence elements {displaystyle n}):

The sequence of each adjacent two numbers merge operation, a {displaystyle ceil (n / 2) } sequences, each sequence comprising two sorted / one element
if the sequence number is not a case the above sequence will merge again, forming {displaystyle ceil (n / 4) } sequences, each sequence comprising four / three elements
repeat step 2 until all the elements sorted, i.e. the sequence number is 1
or more excerpt from Wikipedia

code show as below:

def merge(left, right):
result = []
while left and right:
if left[0] < right[0]:
result.append(left.pop(0))
else:
result.append(right.pop(0))
if left:
result += left
if right:
result += right
return result

def merge_sort(numberlist):
if len(numberlist) <= 1:
return numberlist
mid = len(numberlist) // 2
left = numberlist[:mid]
right = numberlist[mid:]

left = merge_sort(left)
right = merge_sort(right)
return merge(left, right)

Sixth, quick sort

Pick out the number of columns in an element, called a "reference" (Pivot),
reordering columns, all smaller than the reference value is placed in front of the reference element, all larger than the reference value elements placed behind the reference (the same number can be to either side). After the end of this division, in an intermediate position on the reference sequence. This division is called (Partition) operation.
Recursively (Recursively) than the reference value the number of columns and the sub-element is greater than the reference value of the child element number column.
Recursive to the bottom, the size is the number of columns or a zero, that is already sorted better. This algorithm will end, because in each iteration (iteration), which will at least one element placed in its final position to go.

Above excerpt from Wikipedia

code show as below:

def quick_sort(array):
if len(array) < 2:
return array
else:
pivot = array[0]
less = [i for i in array[1:] if i <= pivot]
greater = [i for i in array[1:] if i > pivot]
return quick_sort(less) + [pivot] + quick_sort(greater)
七、堆排序

In terms of instructions in ascending order, the array into the maximum stack (Max-Heap Heap), which is a bulk properties meet the maximum (Max-Heap Property) of a binary tree: For each node except the root i, A [parent (i)] ≥ A [i].

Repeat the maximum value taken from the maximum stack node (the root node and the last exchange, the last switching node after the removal of the stack), and so maintaining the maximum accumulation of the residual bulk properties.

def heap_sort(numberlist):
length = len(numberlist)
def sift_down(start, end):
root = start
while True:
child = 2 * root + 1
if child > end:
break
if child + 1 <= end and numberlist[child] < numberlist[child + 1]:
child += 1
if numberlist[root] < numberlist[child]:
numberlist[root], numberlist[child] = numberlist[child], numberlist[root]
root = child
else:
break

Creating maximum heap

for start in range((length - 2) // 2, -1, -1):
    sift_down(start, length - 1)

Heapsort

for end in range(length - 1, 0, -1):
    numberlist[0], numberlist[end] = numberlist[end], numberlist[0]
    sift_down(0, end - 1)

return numberlist

Eight, counting sort
above excerpt from Wikipedia
code is as follows:

def counting_sort (numberlist, maxnumber): # maxnumber the maximum array
length = len (numberlist) # to be sorted array length
b = [0 for i in range (length)] # set the output sequence, is initialized to 0
C = [ 0 for i in range (maxnumber + 1)] # set technology sequence is initialized to 0
for J in numberlist,:
C [J] = C [J] +. 1
for I in Range (. 1, len ©):
C [I] = C [I] + C [I -. 1]
for J in numberlist,:
B [C [J] -. 1] = J
C [J] = C [J] -. 1
return B
of this article by reference Wikipedia and eight sorting algorithm python achieve compilations

Published 25 original articles · won praise 0 · Views 6500

Guess you like

Origin blog.csdn.net/lynchyueliu/article/details/104515573