「插入排序法」修訂間的差異
跳至導覽
跳至搜尋
Tankianting(討論 | 貢獻) |
Tankianting(討論 | 貢獻) |
||
行 1: | 行 1: | ||
{{Nav|程式語言、邏輯學}} | {{Nav|程式語言、邏輯學}} | ||
insert_sort.py | |||
<pre> | <pre> | ||
#!/usr/bin/env python | |||
#合併排序法 marge sort | |||
import math | |||
def | def merge_sort_aux(array, p, q): | ||
mean = math.floor((p+q)/2) | |||
if q - p <= 1: | |||
return array | |||
else: | |||
print(p, q, mean,array[p:q]) | |||
array = merge_sort_aux(array, p, mean) | |||
array = merge_sort_aux(array, mean,q) | |||
array = merge(array, p, mean, q) | |||
return array | |||
def merge(array, l, m, r): | |||
array_l = array[l:m] | |||
array_r = array[m:r] | |||
i = 0 | |||
j = 0 | |||
k = l | |||
array_l_length = m - l | |||
array_r_length = r - m | |||
while i < array_l_length and j < array_r_length: | |||
if array_l[i] <= array_r[j]: | |||
array[k] = array_l[i] | |||
i += 1 | |||
else: | |||
array[k] = array_r[j] | |||
j += 1 | |||
k += 1 | |||
if i == array_l_length: | |||
while j < array_r_length: | |||
array[k] = array_r[j] | |||
j += 1 | |||
k += 1 | |||
if j == array_r_length: | |||
while i < array_l_length: | |||
array[k] = array_l[i] | |||
i += 1 | |||
k += 1 | |||
return array | |||
def merge_sort(array): | |||
return merge_sort_aux(array, 0, len(array)) | |||
array = [3,1,4,1,5,9,2,6] | |||
print(merge_sort(array)) | |||
[[category:演算法]] | [[category:演算法]] |
於 2024年12月12日 (四) 23:09 的最新修訂
insert_sort.py
#!/usr/bin/env python #合併排序法 marge sort import math def merge_sort_aux(array, p, q): mean = math.floor((p+q)/2) if q - p <= 1: return array else: print(p, q, mean,array[p:q]) array = merge_sort_aux(array, p, mean) array = merge_sort_aux(array, mean,q) array = merge(array, p, mean, q) return array def merge(array, l, m, r): array_l = array[l:m] array_r = array[m:r] i = 0 j = 0 k = l array_l_length = m - l array_r_length = r - m while i < array_l_length and j < array_r_length: if array_l[i] <= array_r[j]: array[k] = array_l[i] i += 1 else: array[k] = array_r[j] j += 1 k += 1 if i == array_l_length: while j < array_r_length: array[k] = array_r[j] j += 1 k += 1 if j == array_r_length: while i < array_l_length: array[k] = array_l[i] i += 1 k += 1 return array def merge_sort(array): return merge_sort_aux(array, 0, len(array)) array = [3,1,4,1,5,9,2,6] print(merge_sort(array))