修改归并排序代码:实现字符串按长度从长到短排序
修改归并排序实现字符串按长度降序排列
你需要调整归并排序的比较逻辑,从直接比较整数改为比较字符串长度,同时实现降序(从长到短),另外原代码里还有几处拼写和索引错误需要修正。不需要提前通过for循环遍历存储所有字符串长度,直接在比较时调用len()函数获取当前字符串的长度即可,这样代码更简洁高效。具体修改如下:
核心修改点
- 调整比较规则:在
merge函数的核心比较分支,把原本的整数大小比较,替换为字符串长度的比较,并且为了实现降序,反转判断条件。 - 修正拼写错误:原代码中
merge函数的参数tempory_storage是拼写错误,改为temporary_storage(和merge_sort里的变量名保持一致)。 - 修复索引赋值错误:原代码最后把临时数组内容写回原数组时,
items[start_1 + 1]是错误的,改为items[start_1 + i],否则会把所有值都覆盖到同一个位置。
修改后的完整代码
def merge_sort(items): n = len(items) temporary_storage = [None] * n size_of_subsections = 1 while size_of_subsections < n: for i in range(0, n, size_of_subsections * 2): l1_start, l1_end = i, min(i + size_of_subsections, n) l2_start, l2_end = l1_end, min(l1_end + size_of_subsections, n) sections = (l1_start, l1_end), (l2_start, l2_end) merge(items, sections, temporary_storage) size_of_subsections *= 2 return items def merge(items, sections, temporary_storage): (start_1, end_1), (start_2, end_2) = sections i_1 = start_1 i_2 = start_2 i_t = 0 while i_1 < end_1 or i_2 < end_2: if i_1 < end_1 and i_2 < end_2: # 按字符串长度降序排列:长度更长的优先放入临时数组 if len(items[i_1]) > len(items[i_2]): temporary_storage[i_t] = items[i_1] i_1 += 1 else: temporary_storage[i_t] = items[i_2] i_2 += 1 i_t += 1 elif i_1 < end_1: for _ in range(i_1, end_1): temporary_storage[i_t] = items[i_1] i_1 += 1 i_t += 1 else: for _ in range(i_2, end_2): temporary_storage[i_t] = items[i_2] i_2 += 1 i_t += 1 # 将临时数组的排序结果写回原数组对应区间 for i in range(i_t): items[start_1 + i] = temporary_storage[i] return
测试示例
test_strings = ["apple", "banana", "cherry", "date", "blueberry"] sorted_strings = merge_sort(test_strings) print(sorted_strings) # 输出:['blueberry', 'banana', 'cherry', 'apple', 'date']
内容的提问来源于stack exchange,提问作者Vaashen Dhanpat
相关产品推荐
相关产品推荐

