current position:Home>Python data structure implements various sorting algorithms (including algorithm introduction and stability, complexity summary)
Python data structure implements various sorting algorithms (including algorithm introduction and stability, complexity summary)
2023-01-25 11:20:48【Joker-Tong】
PythonThe data structure implements various sorting algorithms(Including algorithm introduction and stability,Complexity summary)
All algorithm performance comparisons
冒泡排序
算法介绍
代码实现
def bubble_sort(num):
for j in range(len(num) - 1, 0, -1):
# j表示每次遍历需要比较的次数,是逐渐减小的
for i in range(j):
if num[i] > num[i + 1]:
num[i], num[i + 1] = num[i + 1], num[i]
Time complexity and stability
最优时间复杂度:O(n) (表示遍历一次发现没有任何可以交换的元素,排序结束.)
最坏时间复杂度:O(n2)
稳定性:稳定
选择排序
算法介绍
代码实现
def selection_sort(alist):
''' 选择排序 :param alist: :return: '''
n = len(alist)
# 需要进行n-1次选择操作
for i in range(n - 1):
# 记录最小位置
min_index = i
# 从i+1位置到末尾选择出最小数据
for j in range(i + 1, n):
if alist[j] < alist[min_index]:
min_index = j
# 如果选择出的数据不在正确位置,进行交换
if min_index != i:
alist[i], alist[min_index] = alist[min_index], alist[i]
Time complexity and stability
最优时间复杂度:O(n2)
最坏时间复杂度:O(n2)
稳定性:不稳定(考虑升序每次选择最大的情况)
插入排序
算法介绍
代码实现
def insert_sort(alist):
''' 插入排序 :param alist: :return: '''
# 从第二个位置,即下标为1的元素开始向前插入
for i in range(1, len(alist)):
# 从第i个元素开始向前比较,如果小于前一个元素,交换位置
for j in range(i, 0, -1):
if alist[j] < alist[j - 1]:
alist[j], alist[j - 1] = alist[j - 1], alist[j]
Time complexity and stability
最优时间复杂度:O(n) (升序排列,序列已经处于升序状态)
最坏时间复杂度:O(n2)
稳定性:稳定
快速排序
算法介绍
代码实现
def quick_sort(alist, start, end):
"""快速排序"""
# 递归的退出条件
if start >= end:
return
# 设定起始元素为要寻找位置的基准元素
mid = alist[start]
# low为序列左边的由左向右移动的游标
low = start
# high为序列右边的由右向左移动的游标
high = end
while low < high:
# 如果low与high未重合,high指向的元素不比基准元素小,则high向左移动
while low < high and alist[high] >= mid:
high -= 1
# 将high指向的元素放到low的位置上
alist[low] = alist[high]
# 如果low与high未重合,low指向的元素比基准元素小,则low向右移动
while low < high and alist[low] < mid:
low += 1
# 将low指向的元素放到high的位置上
alist[high] = alist[low]
# 退出循环后,low与high重合,此时所指位置为基准元素的正确位置
# 将基准元素放到该位置
alist[low] = mid
# 对基准元素左边的子序列进行快速排序
quick_sort(alist, start, low - 1)
# 对基准元素右边的子序列进行快速排序
quick_sort(alist, low + 1, end)
Time complexity and stability
最优时间复杂度:O(nlogn)
最坏时间复杂度:O(n2)
稳定性:不稳定
希尔排序
算法介绍
希尔排序的基本思想是:将数组列在一个表中并对列分别进行插入排序,重复这过程,不过每次用更长的列(步长更长了,列数更少了)来进行.最后整个表就只有一列了.将数组转换至表是为了更好地理解这算法,算法本身还是使用数组进行排序.
例如,假设有这样一组数[ 13 14 94 33 82 25 59 94 65 23 45 27 73 25 39 10 ]
,如果我们以步长为5开始进行排序,我们可以通过将这列表放在有5列的表中来更好地描述算法,这样他们就应该看起来是这样(竖着的元素是步长组成):
13 14 94 33 82
25 59 94 65 23
45 27 73 25 39
10
然后我们对每列进行排序:
10 14 73 25 23
13 27 94 33 39
25 59 94 65 82
45
将上述四行数字,依序接在一起时我们得到:[ 10 14 73 25 23 13 27 94 33 39 25 59 94 65 82 45 ].这时10已经移至正确位置了,然后再以3为步长进行排序:
10 14 73
25 23 13
27 94 33
39 25 59
94 65 82
45
排序之后变为:
10 14 13
25 23 33
27 25 59
39 65 73
45 94 82
94
最后以1步长进行排序(此时就是简单的插入排序了)
代码实现
def shell_sort(alist):
''' 希尔排序 :param alist: :return: '''
n = len(alist)
# 初始步长
gap = n // 2
while gap > 0:
# 按步长进行插入排序
for i in range(gap, n):
j = i
# 插入排序
while j >= gap and alist[j - gap] > alist[j]:
alist[j - gap], alist[j] = alist[j], alist[j - gap]
j -= gap
# 得到新的步长
gap = gap // 2
Time complexity and stability
最优时间复杂度:根据步长序列的不同而不同
最坏时间复杂度:O(n2)
稳定想:不稳定
归并排序
算法介绍
代码实现
def merge_sort(alist):
if len(alist) <= 1:
return alist
# 二分分解
num = len(alist) // 2
left = merge_sort(alist[:num])
right = merge_sort(alist[num:])
# 合并
return merge(left, right)
def merge(left, right):
''' 合并操作,将两个有序数组left[]和right[]合并成一个大的有序数组 '''
# left与right的下标指针
l, r = 0, 0
result = []
while l < len(left) and r < len(right):
if left[l] < right[r]:
result.append(left[l])
l += 1
else:
result.append(right[r])
r += 1
result += left[l:]
result += right[r:]
return result
Time complexity and stability
最优时间复杂度:O(nlogn)
最坏时间复杂度:O(nlogn)
稳定性:稳定
copyright notice
author[Joker-Tong],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2023/025/202301251110566788.html
The sidebar is recommended
- Based on VirtualBox centos7 virtual machine installation
- JVM process cache - Caffeine
- Code Caprice No24 | Backtracking Algorithm Theoretical Basis, 77. Combination
- The Road to Algorithm Practice——[String] Leetcode 824 Goat Latin
- Git summary - Prompt to submit or temporarily store changes when switching to a branch
- Productivity tools - [gitlab configuration] One-time configuration of GitLab account
- Echo+Vue+ElementUI management background source code
- Revel+Vue+ElementUI framework use and build tutorial
- Basic practice tutorial of Revel+Vue+ElementUI framework
- Go Web Development Revel+Vue+ElementUI Framework Practical Tutorial
guess what you like
Construction and deployment tutorial of Revel+Vue+ElementUI framework
8. Java loop advanced comprehensive exercises - infinite loop and jump control statement, every seven passes, square root, judging whether it is a prime number, guessing number games
Control statement + exception handling perfect lucky draw applet-java basics
9. Java Array Knowledge Encyclopedia
Lucky draw applet-java basics
Java basic implementation calculator applet
The front end of actual combat: copy write millet's official website on the first day
1. Linux application programming and network programming---file IO notes in Linux system
7. Linux application programming and network programming --- thread full solution Notes
[Front-end notes - CSS] 10. Cascading and inheritance + selector
Random recommended
- 8. Linux application programming and network programming---Linux network programming notes
- [Java|golang] 1828. Count the number of points in a circle
- Add environment variables under Linux system and will not overwrite the previous method of adding environment variables
- 2 · Linux application programming and network programming - file attributes notes
- Redis interview questions (classic 7 questions)
- [Front-end notes——CSS] 11. Box model + background and border
- C + + large Numbers together, according to a combined
- 3. Linux application programming and network programming --- get system information notes
- The use and principle of Kafka message queue
- 5. Linux application programming and network programming---signal notes in Linux
- 6 · Linux application programming and system programming - senior IO notes
- Java collection common interview questions (4)
- 072-JAVA project training: Imitation QQ instant messaging software series lecture 7 (explaining the realization of the chat interface and functions)
- Coordination center performance comparison: how zookeeper solves the load balancing problem
- 070-JAVA project training: imitation QQ instant messaging software series lecture five (explain user registration function)
- Ubuntu installation and configuration (brief)
- 073-JAVA project training: imitation QQ instant messaging software series lecture eight (explain query and add friend function)
- SQL injection classification and error injection EXP
- All basic commands in linux fail, showing that the command cannot be found
- 4. Linux application programming and network programming---Linux process full solution notes (difference between process and program)
- Linux system - basic IO
- Hanlp's understanding of user-defined dictionaries (java version)
- Brief description and configuration of Maven
- 071-JAVA project training: imitation QQ instant messaging software series lecture six (explaining the function of QQ main interface)
- 【Maximum LeetCode】January Algorithm Training (12) Linked List
- 【Max LeetCode】January Algorithm Training (13) Doubly Linked List
- [Big Data Management] Java implements Bloom filter
- [Maximum LeetCode] Algorithm training in January (14) stack
- [Machine Learning] Adaboost Integrated Algorithm
- [Big Data Management] Java implements cuckoo filter (CF)
- Chaozhou Xiangqiao: "Charming Ancient City, Cultural Sharing" Spring Festival Intangible Cultural Heritage Market Opens
- [Big data management] Java realizes the dictionary tree TireTree
- [Max LeetCode] January Algorithm Training (11) Matrix
- New Express (Web framework based on HTTP module encapsulation NodeJS)
- JavaScript error-prone questions (stack processing, call function, prototype chain questions)
- Space "travel", lion and crane dance, intangible cultural heritage experience...During the Spring Festival, Zhuhai Jinwan is so fun!
- Wine 8.0 official release: better support for running Windows applications on Linux and other systems
- Zhongke Sugon: Sugon's new computer "participates in" "The Wandering Earth 2"
- Linux actual combat notes finishing (1.24)
- Automatically execute the specified sql when the springBoot project starts