源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python实现的归并排序算法示例

  • 时间:2020-09-23 15:44 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python实现的归并排序算法示例
本文实例讲述了Python实现的归并排序算法。分享给大家供大家参考,具体如下: 归并排序是建立在归并操作上的一种有效的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。 将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并。 Python实现代码如下:
#-*- coding: UTF-8 -*-
import numpy as np
def Merge(a, f, m, l):
  i = f
  j = m + 1
  tmp = []
  while i <= m and j <= l:
    if a[i] <= a[j]:
      tmp.append(a[i])
      i += 1
    else:
      tmp.append(a[j])
      j += 1
  while i <= m:
    tmp.append(a[i])
    i += 1
  while j<= l:
    tmp.append(a[j])
    j+= 1
  i = f
  for x in xrange(0, len(tmp)):
    a[i] = tmp[x]
    i += 1
def MergeSort(a, f, l):
  if f< l:
    m = (l + f) / 2
    MergeSort(a, f, m)
    MergeSort(a, m+1, l)
    Merge(a, f, m, l)
if __name__ == '__main__':
  a = np.random.randint(0, 10, size = 10)
  print "Before sorting..."
  print "---------------------------------------------------------------"
  print a
  print "---------------------------------------------------------------"
  MergeSort(a, 0, a.size-1)
  print "After sorting..."
  print "---------------------------------------------------------------"
  print a
  print "---------------------------------------------------------------"

运行结果: [img]http://files.jb51.net/file_images/article/201711/20171121151352883.jpg?2017102115148[/img] 更多关于Python相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/663.htm]Python数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/946.htm]Python加密解密算法与技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/788.htm]Python编码操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/642.htm]Python函数使用技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/636.htm]Python字符串操作技巧汇总[/url]》及《[url=http://www.1sucai.cn/Special/520.htm]Python入门与进阶经典教程[/url]》 希望本文所述对大家Python程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部