根据维基百科的定义:
插入排序是迭代算法,逐一获得输入数据,逐步产生有序的输出序列。每步迭代中,算法从输入序列中取出一元素,将之插入有序序列中正确的位置。如此迭代直到全部元素有序。
归并排序进行如下迭代操作:首先将原始序列看成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
#在陈越、何钦铭的数据结构课程中有详细的讲解
def insertionSort(lst,lst2):
for num in range(len(lst)-1):
temp = lst[num+1]
i = num+1
while i>0 and lst[i-1]>temp:
lst[i] = lst[i-1]
i -= 1
lst[i] = temp
if lst == lst2:
return True
return False
def insertionSort2(lst):
origin = lst[:]
for num in range(len(lst)-1):
temp = lst[num+1]
i = num+1
while i>0 and lst[i-1]>temp:
lst[i] = lst[i-1]
i -= 1
lst[i] = temp
if lst != origin:
return lst
def getList(lst):
temp = []
for l in lst:
for num in l:
temp.append(num)
return temp
def megre(sortArray1, sortArray2):
retList = []
i = j = 0
while i < len(sortArray1) and j < len(sortArray2):
if sortArray1[i] <= sortArray2[j]:
retList.append(sortArray1[i])
i += 1
else:
retList.append(sortArray2[j])
j += 1
while i < len(sortArray1):
retList.append(sortArray1[i])
i += 1
while j < len(sortArray2):
retList.append(sortArray2[j])
j += 1
return retList
def mergeSort(sortArray1,lst):
sortArray1 = [[x] for x in sortArray1]
while len(sortArray1) > 1 :
i = 0
while i < len(sortArray1)-1:
temp = sortArray1[:]
newList = megre(temp[i],temp[i+1])
sortArray1.pop(i)
sortArray1.pop(i)
sortArray1.insert(i,newList)
i += 1
# print sortArray1
if getList(sortArray1) == lst:
return True
return False
def mergeSort1(sortArray1):
origin = sortArray1[:]
sortArray1 = [[x] for x in sortArray1]
while len(sortArray1) > 1 :
i = 0
while i < len(sortArray1)-1:
temp = sortArray1[:]
newList = megre(temp[i],temp[i+1])
sortArray1.pop(i)
sortArray1.pop(i)
sortArray1.insert(i,newList)
i += 1
# print sortArray1
if getList(sortArray1) != origin:
return getList(sortArray1)
if __name__ == "__main__":
N = int(raw_input())
list1 = [int(x) for x in raw_input().split(" ") if x != ""]
list2 = [int(x) for x in raw_input().split(" ") if x != ""]
if insertionSort(list1[:],list2[:]):
print "Insertion Sort"
print " ".join(str(x) for x in insertionSort2(list2))
elif mergeSort(list1,list2) :
print "Merge Sort"
print " ".join([str(x) for x in mergeSort1(list2)])