python 实现归并排序算法
2019/7/13 22:02:01
本文主要是介绍python 实现归并排序算法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
理论不多说:
#!/usr/bin/python
import sys
def merge(array, q, p, r):
left_array = array[q:p+1]
right_array = array[p+1:r+1]
left_array_num = len(left_array)
right_array_num = len(right_array)
i, j , k= [0, 0, q]
while i < left_array_num and j < right_array_num:
if (left_array[i] < right_array[j]):
array[k] = left_array[i]
i+=1
else:
array[k] = right_array[j]
j+=1
k+=1
while i < left_array_num:
array[k] = left_array[i];
k+=1
i+=1
while j < right_array_num:
array[k] = right_array[j]
k+=1
j+=1
def merge_sort(array, q, r):
if q < r:
p = (q + r) / 2
merge_sort(array, q, p)
merge_sort(array, p + 1, r)
merge(array, q, p, r)
if __name__ == "__main__":
array = [2, 45, 5, 7, 34, 456, 345, 89, 8, 1, 341, 4, 98, 67]
merge_sort(array, 0, len(array) - 1)
for a in array:
sys.stdout.write("%d " % a)
复制代码 代码如下:
#!/usr/bin/python
import sys
def merge(array, q, p, r):
left_array = array[q:p+1]
right_array = array[p+1:r+1]
left_array_num = len(left_array)
right_array_num = len(right_array)
i, j , k= [0, 0, q]
while i < left_array_num and j < right_array_num:
if (left_array[i] < right_array[j]):
array[k] = left_array[i]
i+=1
else:
array[k] = right_array[j]
j+=1
k+=1
while i < left_array_num:
array[k] = left_array[i];
k+=1
i+=1
while j < right_array_num:
array[k] = right_array[j]
k+=1
j+=1
def merge_sort(array, q, r):
if q < r:
p = (q + r) / 2
merge_sort(array, q, p)
merge_sort(array, p + 1, r)
merge(array, q, p, r)
if __name__ == "__main__":
array = [2, 45, 5, 7, 34, 456, 345, 89, 8, 1, 341, 4, 98, 67]
merge_sort(array, 0, len(array) - 1)
for a in array:
sys.stdout.write("%d " % a)
这篇关于python 实现归并排序算法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-24Python编程基础详解
- 2024-11-21Python编程基础教程
- 2024-11-20Python编程基础与实践
- 2024-11-20Python编程基础与高级应用
- 2024-11-19Python 基础编程教程
- 2024-11-19Python基础入门教程
- 2024-11-17在FastAPI项目中添加一个生产级别的数据库——本地环境搭建指南
- 2024-11-16`PyMuPDF4LLM`:提取PDF数据的神器
- 2024-11-16四种数据科学Web界面框架快速对比:Rio、Reflex、Streamlit和Plotly Dash
- 2024-11-14获取参数学习:Python编程入门教程