归并排序 c++ and python

Posted chaosliang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了归并排序 c++ and python相关的知识,希望对你有一定的参考价值。

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;

const int N = 1e5 + 5;

int a[N], tmp[N];

void merge_sort(int q[], int L, int R)
{

    if(L >= R)
        return ;
    int mid = L + R >> 1;
    merge_sort(q, L, mid);
    merge_sort(q, mid + 1, R);
    int k = 0, i = L, j = mid + 1;
    while(i <= mid && j <= R)
        tmp[k ++] = q[i] <= q[j] ? q[i ++] : q[j ++];
    while(i <= mid)
        tmp[k ++] = q[i ++];
    while(j <= R)
        tmp[k ++] = q[j ++];
    for(int i = L, j = 0; i <= R; ++ i, ++ j)
        q[i] = tmp[j];
    return ;
}

int main()
{
    int n;
    scanf("%d", &n);
    for(int i = 0; i < n; ++ i)
        scanf("%d", &a[i]);
    merge_sort(a, 0, n - 1);
    for(int i = 0; i < n; ++ i)
        printf("%d ", a[i]);
    return 0;
}
def merge_sort(q, L, R):
    if L >= R:
        return
    mid = L + R >> 1
    merge_sort(q, L, mid)
    merge_sort(q, mid + 1, R)
    i = L
    j = mid + 1
    tmp = []
    while i <= mid and j <= R:
        if q[i] < q[j]:
            tmp.append(q[i])
            i += 1
        else:
            tmp.append(q[j])
            j += 1
    while i <= mid:
        tmp.append(q[i])
        i += 1
    while j <= R:
        tmp.append(q[j])
        j += 1
    k = 0
    for i in range(L, R + 1):
        q[i] = tmp[k]
        k += 1
    return


n = int(input())
a = list(map(int, input().split()))
merge_sort(a, 0, n - 1)
for i in range(n):
    print(a[i], end=" ")

测试通过题目https://www.acwing.com/problem/content/description/789/

以上是关于归并排序 c++ and python的主要内容,如果未能解决你的问题,请参考以下文章

c++链表归并排序的迭代版本

C++实现归并排序

归并排序 and 快速排序

python代码实现归并排序(Merge Sort )

C++ 随机化快速排序 最简单易懂的代码! 基于归并分区思想实现

Python代码实现归并排序