归并排序的基本思想是: 可以看出归并排序运用了 分而治之的思想 。 归并排序是按照分层进行比较的,会分成 C实现: python实现:
Day_20 —— 归并排序
log2n层;
而每一层的比较次数为
O(n);
所以时间复杂度求得
nlog2n。#include <stdio.h> #define max 10 int a[11] = { -10, 14, 11, 26, 34, 31, -33, 20, 42, 11, 0 }; int b[10]; void merging(int low, int mid, int high) { int l1, l2, i; for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) { if(a[l1] <= a[l2]) b[i] = a[l1++]; else b[i] = a[l2++]; } while(l1 <= mid) b[i++] = a[l1++]; while(l2 <= high) b[i++] = a[l2++]; for(i = low; i <= high; i++) a[i] = b[i]; } void sort(int low, int high) { int mid; if(low < high) { mid = (low + high) / 2; sort(low, mid); sort(mid+1, high); merging(low, mid, high); } else { return; } } int main() { int i; printf("List before sortingn"); for(i = 0; i <= max; i++) printf("%d ", a[i]); sort(0, max); printf("nList after sortingn"); for(i = 0; i <= max; i++) printf("%d ", a[i]); }
def merge_sort(collection): def merge(left, right): result = [] while left and right: result.append((left if left[0] <= right[0] else right).pop(0)) return result + left + right if len(collection) <= 1: return collection mid = len(collection) // 2 return merge(merge_sort(collection[:mid]), merge_sort(collection[mid:])) if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:n").strip() unsorted = [int(item) for item in user_input.split(",")] print(*merge_sort(unsorted), sep=",")
本网页所有视频内容由 imoviebox边看边下-网页视频下载, iurlBox网页地址收藏管理器 下载并得到。
ImovieBox网页视频下载器 下载地址: ImovieBox网页视频下载器-最新版本下载
本文章由: imapbox邮箱云存储,邮箱网盘,ImageBox 图片批量下载器,网页图片批量下载专家,网页图片批量下载器,获取到文章图片,imoviebox网页视频批量下载器,下载视频内容,为您提供.
阅读和此文章类似的: 全球云计算