当前位置:网站首页>归并排序(merge_sort)
归并排序(merge_sort)
2022-07-26 06:34:00 【fiveym】
归并排序的意义及使用
- 假设现在的列表分两段有序,如何将其合称为一个有序列表

def merge(li, low, mid, high):
i = low
j = mid + 1
ltmp = []
while i<=mid and i<=high: #只要左右两边都有数
if li[i] < li[j]:
ltmp.append(li[i])
i += 1
else:
ltmp.append(li[j])
j += 1
#while执行完,肯定有一部分没数了
while i <= mid:
ltmp.append(li[i])
i += 1
while j <= high:
ltmp.append(li[j])
j += 1
li[low:high+1] = ltmp
li = [2,4,5,7,1,3,6,8]
merge(li, 0, 3, 7)
print(li)
如何使用归并
- 分解:将列表越分越小,直至分成一个元素
- 终止条件:一个元素是有序的
- 合并:将两个有序列表归并,列表越来越大
- 时间复杂度为O(logn),空间复杂度为O(n)

def merge_sort(li, low, high):
if low < high:
mid = (low + high) //2
merge_sort(li, low, mid)
merge_sort(li, mid+1, high)
merge(li, low, mid, high)
li = list(range(100))
import random
random.shuffle(li)
print(li)
merge_sort(li, 0, len(li)-1)
print(li)
多种排序的小总结

边栏推荐
- [fault diagnosis] bearing fault diagnosis based on Bayesian optimization support vector machine with matlab code
- Overview of image classification of vision transformer must read series
- CONDA virtual environment envs directory is empty
- 【Day_06 0423】不要二
- [day_040421] calculate candy
- [day_050422] continuous maximum sum
- Go channel
- 【Day05_0422】C语言选择题
- Code Runner for VS Code,下载量突破 4000 万!支持超过50种语言
- nuxt 配置主题切换
猜你喜欢

Do it yourself smart home: intelligent air conditioning control

Leetcode:741. picking cherries

Intelligent fire protection application based on fire GIS system

力扣——3. 无重复字符的最长子串

RNN循环神经网络

Basis of multimodal semantic segmentation

【pytorch】图片增广
![[nanny level] package volume optimization tutorial](/img/45/4ca66b10bb96efeb47501c07972d66.png)
[nanny level] package volume optimization tutorial

C language file operation

YOLOv6:又快又准的目标检测框架开源啦
随机推荐
Gdown Access denied:Cannot retrieve the public link of the file.
Use scanner to get multiple data types from the keyboard
Force buckle - 3. Longest substring without repeated characters
[untitled]
BigDecimal变为负数
Code runner for vs code, with more than 40million downloads! Support more than 50 languages
BPG notes (IV)
CCTV dialogue ZTE: why must the database be in your own hands?
Decomposing a positive integer into prime factors requires decomposing into as many factors as possible.
【Day_04 0421】进制转换
Overview of image classification of vision transformer must read series
Intelligent fire protection application based on fire GIS system
[day_040421] calculate candy
[C language] address book dynamic version and document version
[untitled]
Three skills are needed to engage in SAP related work
[fault diagnosis] bearing fault diagnosis based on Bayesian optimization support vector machine with matlab code
English sentence pattern reference exclusive Edition - attributive clause
【Day_07 0425】Fibonacci数列
Flex layout