题目描述
模板题:归并排序
C++代码
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 1;
void merge_sort(int a[], int l, int r){
if(l >= r)
return;
int mid = l + r >> 1;
merge_sort(a, l, mid);
merge_sort(a, mid + 1, r);
int temp[r - l + 1];
int k = 0, i = l, j = mid + 1;
while(i <= mid && j <= r){
if(a[i] <= a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
while(i <= mid)
temp[k++] = a[i++];
while(j <= r)
temp[k++] = a[j++];
j = l;
for(int i = 0; i < k; i++)
a[j++] = temp[i];
}
int main(){
int arr[N];
int n;
cin >> n;
for(int i = 0; i < n; i++)
cin >> arr[i];
merge_sort(arr, 0, n - 1);
for(int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << "\n";
return 0;
}