三種語言實現歸併排序(C++/Python/Java)

火车驶向云外0218發表於2024-07-23

題目

給定你一個長度為 𝑛 的整數數列。

請你使用歸併排序對這個數列按照從小到大進行排序。

並將排好序的數列按順序輸出。

輸入格式

輸入共兩行,第一行包含整數 𝑛。

第二行包含 𝑛 個整數(所有整數均在 1∼109 範圍內),表示整個數列。

輸出格式

輸出共一行,包含 𝑛 個整數,表示排好序的數列。

資料範圍

1≤n≤1000001≤𝑛≤100000

輸入樣例:

5
3 1 2 4 5

輸出樣例:

1 2 3 4 5

C++

#include <bits/stdc++.h>

using namespace std;

const int N = 100010;
int a[N];
int tmp[N];

void merge_sort(int l, int r)
{
    if(l >= r)  return;
    int mid = (l+r) >> 1;
    merge_sort(l, mid);
    merge_sort(mid+1, r);
    int i = l, j = mid + 1;
    int k = l;
    while(i <= mid && j <= r)
    {
        if(a[i] <= a[j]) tmp[k++] = a[i++];
        else tmp[k++] = a[j++];
    }
    while(i <= mid) tmp[k++] = a[i++];
    while(j <= r) tmp[k++] = a[j++];
    for(int t = l; t <= r; t++)
        a[t] = tmp[t];
}

int main()
{
    int n;
    cin >> n;
    for(int i = 0; i < n; i++)
        cin >> a[i];
    merge_sort(0,n-1);
    for(int i = 0; i < n; i++)
        cout << a[i] << " ";
}

Python

n = int(input())
a = [int(x) for x in input().split()]

tmp = [i for i in range(n)]

def merge_sort(l, r):
    if l >= r:
        return
    mid = (l + r) >> 1
    merge_sort(l, mid)
    merge_sort(mid+1, r)
    i, j = l, mid + 1
    k = l
    while i <= mid and j <= r:
        if a[i] <= a[j]:
            tmp[k] = a[i]
            i += 1
        else:
            tmp[k] = a[j]
            j += 1
        k += 1
    
    while i <= mid:
        tmp[k] = a[i]
        i += 1
        k += 1
    
    while j <= r:
        tmp[k] = a[j]
        j += 1
        k += 1
    
    for t in range(l ,r+1):
        a[t] = tmp[t]

merge_sort(0, n-1)
for x in a:
    print(x, end=" ")

Java

import java.util.*;

public class Main{
    static public void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        int [] tmp = new int[n];
        for(int i = 0; i < n; i++)
            a[i] = sc.nextInt();
        merge_sort(a, tmp, 0, n-1);
        for(int i = 0; i < n; i++)
            System.out.print(a[i] + " ");
    }
    static public void merge_sort(int[] a, int[] tmp, int l, int r){
        if(l >= r)  return;
    
        int mid = (l + r) >> 1;
        merge_sort(a, tmp, l, mid);
        merge_sort(a, tmp, mid+1, r);
        int i = l, j = mid + 1;
        
        int k = l;
        while(i <= mid && j <= r){
            if(a[i] <= a[j])    tmp[k++] = a[i++];
            else tmp[k++] = a[j++];
        }
        while(i <= mid) tmp[k++] = a[i++];
        while(j <= r)   tmp[k++] = a[j++];
        for(int t = l; t <= r; t++)
            a[t] = tmp[t]; 
    }
}

相關文章