kikaylee 2020-01-10
#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/
排序是将一串数据按照其某个或者某些关键字的大小进行递增或递减排列的操作我,通常指的排序是升序,排序方式是原地排序。即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并