Abstract: In programming, sorting is an important algorithm, which can help us locate data faster and easier. In this article, we will use the sorting algorithm classifier to sort our arrays and understand how they work.
This article is shared from Huawei Cloud Community " Python Sorting Algorithm Guide ", the original author: Tang Li.
In programming, sorting is an important algorithm that can help us locate data faster and easier. In this article, we will use the sorting algorithm classifier to sort our arrays and understand how they work. In order to ensure the readability of this article, only 4 sorting algorithms are introduced here.
- Bubble Sort
- Insertion sort.
- Merge and sort.
- Quick sort
Bubble Sort
Bubble sort is a simple sorting algorithm that compares the order of two adjacent objects and exchanges the positions of adjacent objects in an unexpected order. Here are its working steps:
- Compare the first and second objects, and if the first is greater than the second, swap them.
- Compare the second object with the third object and check the same conditions. And so on until the last number in the array is compared.
- Repeat this process so that the array is arranged from small to large from left to right.
code show as below
# Python中的冒泡排序
def bubbleSort(array):
# 外循环访问数组的每个元素
for i in range(len(array)):
# 内循环将数组元素与外循环迭代元素进行比较
for j in range(0, len(array) - i - 1):
# 比较两个相邻元素
if array[j] > array[j + 1]:
# 如果元素不是预期顺序则交换元素
temp = array[j]
array[j] = array[j+1]
array[j+1] = temp
data = [5, 4, 3, 2, 1]
bubbleSort(data)
print('Sorted Array')
print(data)
#output: [1, 2, 3, 4, 5]
Insertion sort
Insertion sorting is also very simple. It is divided into two parts: sorted and unsorted. Select the unsorted part and place it in the sorting part correctly. In a similar card game, we have classification cards in hand. Here are its working steps:
- Traverse the array to find the index of the lowest element and swap it with the first element of the array.
- Find the other lowest element in the array (excluding the first element), swap it with the second element, and repeat the operation until the last element of the array.
- In this way, the lowest element in the array will be moved to the left, and the largest element will be on the right of the array, so the array is ordered.
code show as below
# Python中的排序算法
def insertionSort(array):
for step in range(1, len(array)):
key = array[step]
j = step - 1
# 将键与其左侧的每个元素进行比较,直到找到小于它的元素
while j >= 0 and key < array[j]:
array[j + 1] = array[j]
j = j - 1
# 将键放在比它小的元素之后。
array[j + 1] = key
data = [11, 4, 3, 2, 12]
insertionSort(data)
print("sorted array")
print(data)
#output: [2, 3, 4, 11, 12]
Merge sort
Merge sorting is the most commonly used sorting algorithm based on the principle of divide and conquer algorithm. We divide the array into multiple parts, then sort them, and finally merge the sub-parts into a sorted array. For a better understanding, the following are its working steps:
- Divide the array into small pieces until there are no individual elements in each piece.
- Compare each array and place the minimum value on the left and the maximum value on the right side of the array.
- If you find it difficult to understand, take a look at this animated picture.
code show as below
# Python的归并排序
def mergeSort(array):
if len(array) > 1:
# r 是将数组分为两半后的分割点
r = len(array)//2
L = array[:r]
M = array[r:]
# 通过递归方法对两半进行排序
mergeSort(L)
mergeSort(M)
i = j = k = 0
# 直到我们到达 L 或 M 的任一端,从中选择较大的元素 L 和 M 并将它们放置在 A[p 到 r] 处的正确位置
while i < len(L) and j < len(M):
if L[i] < M[j]:
array[k] = L[i]
i += 1
else:
array[k] = M[j]
j += 1
k += 1
# 将L或者M里的元素排序好后,将剩余的元素并放入 A[p to r]
while i < len(L):
array[k] = L[i]
i += 1
k += 1
while j < len(M):
array[k] = M[j]
j += 1
k += 1
array = [8, 6, 14, 12, 10, 3]
mergeSort(array)
print("Sorted array: ")
print(array)
#output: [3, 6, 8, 10, 12, 14]
Quick sort
Like merge sort, quick sort is also a sorting algorithm based on the principle of divide and conquer algorithm. It selects an element as the pivot and partitions the array around the pivot. Here are its working steps:
- Choose a turning point, which can be chosen at random. It is assumed here that we choose the last element of the array as the axis.
- Place all items smaller than the axis on the left, and items larger than the axis on the right of the array.
- Repeat the above steps on the left and right sides of the pivot.
# Python中的快速排序
# 找到分区位置
def partition(array, lowest, highest):
# 这里我们选择最右的元素作为枢轴
pivot = array[highest]
# 为最大的元素设置指针
i = lowest - 1
# 将每个元素与枢轴元素对比
for j in range(lowest, highest):
if array[j] <= pivot:
i = i + 1
# 将 i 处的元素与 j 处的元素交换
(array[i], array[j]) = (array[j], array[i])
# 将枢轴元素与 i 指定的较大元素交换
(array[i + 1], array[highest]) = (array[highest], array[i + 1])
# 返回分区完成的位置
return i + 1
def quickSort(array, lowest, highest):
if lowest < highest:
# 找到枢轴元素
# 小于枢轴的元素放左边
# 大于枢轴的元素放右边
pi = partition(array, lowest, highest)
# 枢轴左侧的递归调用
quickSort(array, lowest, pi - 1)
# 枢轴右侧的递归调用
quickSort(array, pi + 1, highest)
array = [9, 8, 3, 2, 1, 10, 7, 6, 19]
size = len(array)
quickSort(array, 0, size - 1)
print('Sorted Array is below')
print(array)
#output [1, 2, 3, 6, 7, 8, 9, 10, 19]
The above is the entire content of this article, thanks for reading, if it is helpful to you, I hope to like it~
Original address: https://python.plainenglish.io/a-guide-to-sorting-algorithms-in-python-dfa9436b8527
Click to follow and learn about Huawei Cloud's fresh technology for the first time~
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。