当前位置:网站首页>AcWing 787. 归并排序(模板)
AcWing 787. 归并排序(模板)
2022-07-03 08:49:00 【Sasakihaise_】
【归并排序】和快排一样也是分治的思想
(1)确定分界点
(2)分界点两侧分别排序
(3)合并两个排好序的数组
(4)复制回原数组中
妥妥的O(nlogn)的时间复杂度,合并需要用O(n)的时间,共logn层
package AcWing.course;
import java.io.StreamTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class _787_归并排序_1 {
// 8:38 8:50
static int n;
static int[] arr, tmp;
static StreamTokenizer st;
static int nextInt() throws Exception {
st.nextToken();
return (int)st.nval;
}
static void mergeSort(int l, int r){
if(l >= r) return;
int mid = (l + r) >>> 1, i = l, j = mid + 1, k = 0;
mergeSort(l, mid); mergeSort(mid + 1, r);
while(i <= mid && j <= r){
if(arr[i] <= arr[j]) tmp[k++] = arr[i++];
else tmp[k++] = arr[j++];
}
while(i <= mid) tmp[k++] = arr[i++];
while(j <= r) tmp[k++] = arr[j++];
for(i = l, j = 0; j < k; j++, i++) arr[i] = tmp[j];
}
public static void main(String[] args) throws Exception {
st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter pw = new PrintWriter(System.out);
n = nextInt();
arr = new int[n];
tmp = new int[n];
for(var i = 0; i < n; i++) arr[i] = nextInt();
mergeSort(0, n - 1);
for(var x: arr){
pw.print(x);
pw.print(" ");
}
pw.flush();
}
}
边栏推荐
- Six dimensional space (C language)
- Unity notes 1
- 22-06-27 Xian redis (01) commands for installing five common data types: redis and redis
- [concurrent programming] thread foundation and sharing between threads
- Final review of Database Principles
- DOM render mount patch responsive system
- 22-06-28 西安 redis(02) 持久化机制、入门使用、事务控制、主从复制机制
- Downward compatibility and upward compatibility
- file_ put_ contents
- Drawing maze EasyX library with recursive backtracking method
猜你喜欢

Unity Editor Extension - drag and drop

XPath实现XML文档的查询

Deep parsing (picture and text) JVM garbage collector (II)

Monotonic stack -503 Next bigger Element II

数据库原理期末复习

22-06-28 西安 redis(02) 持久化机制、入门使用、事务控制、主从复制机制

记忆化搜索 AcWing 901. 滑雪

Monotonic stack -84 The largest rectangle in the histogram

Redux - learning notes

Phpstudy 80 port occupied W10 system
随机推荐
PHP function date (), y-m-d h:i:s in English case
Concurrent programming (V) detailed explanation of atomic and unsafe magic classes
[rust notes] 09- special types and generics
Location of package cache downloaded by unity packagemanager
Solution of 300ms delay of mobile phone
单调栈-84. 柱状图中最大的矩形
Es8 async and await learning notes
我们有个共同的名字,XX工
[concurrent programming] working mechanism and type of thread pool
Analysis of Alibaba canal principle
单调栈-503. 下一个更大元素 II
Collection interface
Debug debugging - Visual Studio 2022
剑指 Offer II 091. 粉刷房子
Monotonic stack -503 Next bigger Element II
Facial expression recognition based on pytorch convolution -- graduation project
求组合数 AcWing 886. 求组合数 II
Introduction to the usage of getopts in shell
JS non Boolean operation - learning notes
TP5 order multi condition sort