python實現歸併排序

2021-10-04 10:19:34 字數 2081 閱讀 1608

python實現**

建立隨機數組生成程式:random_list.py

#-*- coding:utf-8 -*-

# created date: 2020/03/10

import random

defrandom_list

(n):

"""返回乙個長度為n的隨機數列表,數值為[0,1000)"""

print

("input number is :{}"

.format

(n))

ilist =

for num in

range

(n):

1000))

return ilist

if __name__ ==

"__main__"

: ilist = random_list(10)

print

(ilist)

建立歸併排序演算法程式:merge_sort.py

#-*- coding:utf-8 -*-

#created date: 2020/03/16

from random_list import random_list

import timeit

import sys

num = sys.ar**[1]

ilist = random_list(

int(num)

)def

merge_sort

(ilist)

:'''建立拆分函式,將乙個數列拆分成兩個數列'''

iflen

(ilist)

<=1:

return ilist

middle =

len(ilist)//2

left, right = ilist[

0:middle]

, ilist[middle:

]""" 通過遞迴的方式,呼叫merge_sort()函式,將拆分後的數列繼續不停的拆分,直到每個數列長度為1

然後呼叫merge_list()函式,將拆分的數列合併排序為1個數列

"""return merge_list(merge_sort(left)

, merge_sort(right)

)def

merge_list

(left, right)

:'''建立合併函式,將兩個數列合併成乙個數列'''

mlist =

while left and right:

if left[0]

>= right[0]

:0))

else:0

))while left:0)

)while right:0)

)return mlist

if __name__ ==

"__main__"

:print

("source list: {}"

.format

(ilist)

)print

("sorted results: {}"

.format

(merge_sort(ilist)))

print

(timeit.timeit(

"merge_sort(ilist)"

,"from __main__ import merge_sort, ilist"

, number =

1000

))

在命令列輸入指令:

python merge_sort.py 10
得到排序結果為:

input number is :10

source list: [703, 936, 227, 427, 471, 74, 114, 797, 635, 329]

sorted results: [74, 114, 227, 329, 427, 471, 635, 703, 797, 936]

0.0283238

python實現歸併排序

歸併排序,先把陣列按中間分為2個單元,直至每個單元僅包含1個元素,然後依次合併2個單元至一臨時陣列 def merge str,start index,end index,mid,temp j start index k mid 1 i 0while j mid and k end index if...

Python實現歸併排序

def mergesort seq if len seq 1 return seq else mid int len seq 2 lpart mergesort seq mid rpart mergesort seq mid return merge lpart,rpart defmerge lpa...

Python實現歸併排序

歸併排序是典型的分治法的應用 思想 先遞迴分解陣列,再合併陣列 原理 將陣列分解最小之後,然後合併兩個有序陣列,基本思想是比較兩個陣列的最前面的數,誰小就取誰,取完後,將相應的指標後移以為。然後再比較,直到乙個陣列為空,最後把另乙個陣列的剩餘部分複製過來即可。python 實現 歸併排序 def m...