当前位置:网站首页>空间复杂度为O(1)的归并排序
空间复杂度为O(1)的归并排序
2022-08-10 00:54:00 【qnner】
前言
最近楼主在刷算法题目,刷到了归并排序。自己简单实现后,再次跟常见的归并排序比较,发现空间复杂度更低。所以记录本文用于比较两种算法的实现方式。
经典实现方式:空间复杂度O(n)
这里不再赘述,贴一篇牛客网写的比较详细的帖子:https://www.nowcoder.com/discuss/968849?type=all&order=recall&pos=&page=1&ncTraceId=&channel=-1&source_id=search_all_nctrack&gio_id=8AD3C350B55856EAFE45974949E1359F-1660059896728
复杂度分析:
- 时间复杂度 NlogN
- 空间复杂度 O(N)
我的实现
思路
重点是merge函数。merge函数的作用是合并两个已经排序的数组。我这里的大致思路是,将其中一个数组作为基,把另外一个数组的每一个元素都插入到这个基里面去。
代码实现
def cmp(left, mid):
return left > mid
def merge(arr, left, mid, right):
while mid < right:
for move_left in range(left, mid):
if cmp(arr[move_left], arr[mid]):
tmp = arr[move_left]
for i in range(move_left, mid):
arr[move_left] = arr[i + 1]
arr[i + 1] = tmp
tmp = arr[move_left]
left = move_left
break
mid += 1
def merge_sort(arr, l=None, r=None):
if l is None:
l = 0
if r is None:
r = len(arr)
if l == r -1:
return arr
else:
mid = int((l + r) / 2)
merge_sort(arr, l, mid)
merge_sort(arr, mid + 1, r)
merge(arr, l, mid, r)
if __name__ == '__main__':
arr = [12, 2, 3]
merge_sort(arr)
print(arr)
可以看见,在merge的时候,并没有使用额外的数组空间,所以空间复杂度为O(1)
边栏推荐
- oracle的数据导入导出
- Visual low-code system practice based on design draft identification
- D-Biotinol Involved by Biotin, CAS No: 53906-36-8 Specific Properties Description
- 对修饰器的实验支持功能在将来的版本中可能更改。在 “tsconfig“ 或 “jsconfig“ 中设置 “experimentalDecorators“ 选项以删除此警告
- 什么是 PWA
- 将string类对象中的内容格式化到字符串Buffer中时遇到的异常崩溃分析
- Solidity最强对手:MOVE语言及新公链崛起
- Fedora 36 dnf 安装ModSecurity和 OWASP 核心规则集
- 开发IM即时通讯容易吗?需要什么技术
- HCIP——综合交换实验
猜你喜欢
unity 报错 Unsafe code may only appear if compiling with /unsafe. Enable “Allow ‘unsafe‘ code“ in Pla
惊掉你下巴,程序员编码竟然可以被 996 指数化
基于Web的疫情隔离区订餐系统
UI遍历的初步尝试
Mysql database ALTER basic operations
02| operator
嵌入式Qt-实现两个窗口的切换
MySQL最大连接数限制如何修改
Pagoda measurement - building LightPicture open source map bed system
HCIP——综合交换实验
随机推荐
C language pointer practice questions
头脑风暴:单词拆分
Visual low-code system practice based on design draft identification
oracle的数据导入导出
Moonbeam网络维护模式(Maintenance Mode)解读
assert利用蚁剑登录
Shader Graph learns various special effects cases
力扣每日一题-第51天-744. 寻找比目标字母大的最小字母
CVPR22 Oral|通过多尺度token聚合分流自注意力,代码已开源
宽带由20M换为100M
以太网PHY芯片LAN8720A芯片研究
Biotin-Cy2 Conjugate, Biotin-Cy2 Conjugate_Cy2 Biotin Conjugate
Docker interview question 2--get the number of database connections and docker-compose
基于Web的疫情隔离区订餐系统
【Grpc】报错:status = StatusCode.UNIMPLEMENTED details = ““
Not, even the volume of the king to write code in the company are copying and pasting it reasonable?
Unity reports Unsafe code may only appear if compiling with /unsafe. Enable “Allow ‘unsafe’ code” in Pla
Xi'an biotin-tetrapolyethylene glycol-amide-4phenol light yellow semi-solid
3438. 数制转换
Fedora 36 dnf 安装ModSecurity和 OWASP 核心规则集