三种语言实现归并排序(C++/Python/Java)
题目
给定你一个长度为 𝑛 的整数数列。
请你使用归并排序对这个数列按照从小到大进行排序。
并将排好序的数列按顺序输出。
输入格式
输入共两行,第一行包含整数 𝑛。
第二行包含 𝑛 个整数(所有整数均在 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];
}
}