您的位置:首页 > 编程语言 > Python开发

分治排序算法的python实现

2014-03-31 16:01 232 查看
时间复杂度O(NlgN)

分治模式的一般步骤:

分解(Divide):将原问题分解成一些列子问题;

解决(Conquer):递归地解各子问题,若子问题足够小,则直接求解;

合并(Combine):将子问题的结果合并成原问题的解。

以下是分治排序的python实现:

def merge(p_list,p_start,p_mid,p_end):
left_list = p_list[p_start:p_mid+1];
right_list = p_list[p_mid+1:p_end+1];
left_index = right_index = 0;
for i in xrange(p_start,p_end+1):
if left_index >= len(left_list) or right_index >= len(right_list):
break;
if left_list[left_index] <= right_list[right_index]:
p_list[i] = left_list[left_index];
left_index += 1;
else:
p_list[i] = right_list[right_index];
right_index += 1;
if left_index >= len(left_list):
p_list[i:p_end+1] = right_list[right_index:len(right_list)];
else:
p_list[i:p_end+1] = left_list[left_index:len(left_list)];

def merge_sort(p_list,p_start,p_end):
if p_start < p_end:
mid = (p_start + p_end) >> 1;
merge_sort(p_list,p_start,mid);
merge_sort(p_list,mid+1,p_end);
merge(p_list,p_start,mid,p_end);


enjoy it.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: