$$\color{Red}{归并排序-三种语言代码}$$
我的网站=> 分享了我关于前后端的各种知识和生活美食~
我于Acwing平台分享的零散刷的各种各样的题
题目介绍
给定你一个长度为 n 的整数数列。
请你使用归并排序对这个数列按照从小到大进行排序。
并将排好序的数列按顺序输出。
输入格式
输入共两行,第一行包含整数 n。
第二行包含 n 个整数(所有整数均在 1 ∼ 10 ^ 9 范围内),表示整个数列。
输出格式
输出共一行,包含 n 个整数,表示排好序的数列
数据范围
1 ≤ n ≤ 100000
输入样例:
5
3 1 2 4 5
输出样例:
1 2 3 4 5
java 解法
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int N = 100010, n;
static int[] a = new int[N];
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static void merge_sort(int l, int r, int[] a) {
if (l >= r) return;
int mid = l + r >> 1;
merge_sort(l, mid, a);
merge_sort(mid + 1, r, a);
int [] back = new int[r - l + 1];
int i = l, j = mid+1, k = 0;
while (i <= mid && j <= r){
if (a[i] <= a[j]) back[k++] = a[i++];
else back[k++] = a[j++];
}
while (i <= mid) back[k++] = a[i++];
while (j <= r) back[k++] = a[j++];
i = l;
j = 0;
while (i <= r) a[i++] = back[j++];
}
public static void main(String[] args) throws IOException {
n = Integer.parseInt(br.readLine());
String [] s = br.readLine().split(" ");
for (int i = 0; i < n; i++) a[i] = Integer.parseInt(s[i]);
merge_sort(0, n-1, a);
for (int i = 0; i < n; i++) System.out.print(a[i] + " ");
}
}
C++ 解法
#include<iostream>
using namespace std;
int n;
const int N = 100000;
int q[N], tem[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)
{
if(q[i] <= q[j]) tem[k++] = q[i++];
else tem[k++] = q[j++];
}
while(i <= mid) tem[k++] = q[i++];
while(j <= r) tem[k++] = q[j++];
k = 0;
while(l <= r) q[l++] = tem[k++];
}
int main()
{
scanf("%d", &n);
for(int i=0; i<n; i++) cin >> q[i];
merge_sort(q, 0, n-1);
for(int i=0; i<n; i++) cout << q[i] << ' ';
return 0;
}
python3 解法
def merge_sort(q, l, r):
if l >= r:
return
mid = (l + r) // 2
merge_sort(q, l, mid), merge_sort(q, mid+1, r)
i, j = l, mid + 1
tem = []
while i <= mid and j <= r:
if q[i] <= q[j]:
tem.append(q[i])
i += 1
else:
tem.append(q[j])
j += 1
while i <= mid:
tem.append(q[i])
i += 1
while j <= r:
tem.append(q[j])
j += 1
q[l:r+1] = tem
if __name__ == '__main__':
n = int(input())
q = [int(x) for x in input().split()]
merge_sort(q, 0, n-1)
for i in q:
print(i, end=' ')