1035
根据维基百科的定义:
插入排序是迭代算法,逐一获得输入数据,逐步产生有序的输出序列。每步迭代中,算法从输入序列中取出一元素,将之插入有序序列中正确的位置。如此迭代直到全部元素有序。
归并排序进行如下迭代操作:首先将原始序列看成 N 个只包含 1 个元素的有序子序列,然后每次迭代归并两个相邻的有序子序列,直到最后只剩下 1 个有序的序列。
现给定原始序列和由某排序算法产生的中间序列,请你判断该算法究竟是哪种排序算法?
输入格式:
输入在第一行给出正整数 N (≤100);随后一行给出原始序列的 N 个整数;最后一行给出由某排序算法产生的中间序列。这里假设排序的目标序列是升序。数字间以空格分隔。
输出格式:
首先在第 1 行中输出Insertion Sort表示插入排序、或Merge Sort表示归并排序;然后在第 2 行中输出用该排序算法再迭代一轮的结果序列。题目保证每组测试的结果是唯一的。数字间以空格分隔,且行首尾不得有多余空格。
输入样例 1:
10
3 1 2 8 7 5 9 4 6 0
1 2 3 7 8 5 9 4 6 0
输出样例 1:
Insertion Sort
1 2 3 5 7 8 9 4 6 0
输入样例 2:
10
3 1 2 8 7 5 9 4 0 6
1 3 2 8 5 7 4 9 0 6
输出样例 2:
Merge Sort
1 2 3 8 4 5 7 9 0 6
思路 这题一开始没有任何思路,在网上查了插入排序于归并排序的具体原理,只搞懂部分插入排序,归并排序没弄懂,只勉强做出插入排序。
代码:
package test1;
import java.util.Scanner;
public class PTA1035 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int[] a=new int[n];
int[] b=new int[n];
for(int i=0;i<n;i++){
a[i]=in.nextInt();
}
for(int i=0;i<n;i++){
b[i]=in.nextInt();
}
for(int i=0;i<(int)Math.floor(n/2);i++){
int currenta = a[i];
int j = i - 1;
while (j >= 0 && a[j] > currenta) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = currenta;
}
int t=0;
while (a[t]==b[t]&&t<(int)Math.floor(n/2)){
t=t+1;
}
if(t==(int)Math.floor(n/2)) {
System.out.println("Insertion Sort");
}
int currenta=a[(int) Math.floor(n/2)];
int j= (int) (Math.floor(n/2)-1);
while (j>=0&&a[j]>currenta){
a[j+1]=a[j];
j--;
}
a[j+1]=currenta;
for(int i=0;i<n;i++){
System.out.print(a[i]);
if(i<n-1){
System.out.print(" ");
}
}
}
}