非递归合并排序
Description
合并(归并)排序的核心思想是:每次从中间位置将数组分组再分别排序。请实现其非递归方案。
Input
输入的每一行表示一个元素为正整数的数组,所有值用空格隔开,第一个值为数值长度,其余为数组元素值。
Output
输出的每一行为排序结果,用空格隔开,末尾不要空格。
Sample Input 1
13 24 3 56 34 3 78 12 29 49 84 51 9 100
Sample Output 1
3 3 9 12 24 29 34 49 51 56 78 84 100
'''
'''
归并排序的非递归版本有点不一样,需要自底向上来进行,也就是最初是1-2个元素排序
参考:https://www.cnblogs.com/yulinfeng/p/7078661.html?utm_source=itdadao&utm_medium=referral
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: Problem8
Description :
Author : xszhou
date: 2019/1/8
-------------------------------------------------
"""
__author__ = 'xszhou'
import sys
import collections
# 递归归并排序
def mergeSortR(arr):
segment(arr,0,len(arr)-1)
def segment(arr,left,right):
if left >= right:
return
center = int((left+right)/2)
segment(arr,left,center)
segment(arr,center+1,right)
merge(arr,left,center,right)
# 非递归归并排序
def mergeSortNoR(arr):
len_step = 1
while len_step <= len(arr):
i = 0
while i + len_step <= len(arr):
low = i
mid = i + len_step - 1
high = i + 2 * len_step - 1
if high > len(arr) - 1:
high = len(arr) - 1
merge(arr,low,mid,high)
i += len_step * 2
len_step *= 2
def merge(arr, low, mid, high):
tmpArray = [0 for i in range(len(arr))]
rightIndex = mid+1
tmpIndex = low
begin = low
while low <= mid and rightIndex <= high:
if arr[low]<=arr[rightIndex]:
tmpArray[tmpIndex] = arr[low]
low+=1
tmpIndex+=1
else:
tmpArray[tmpIndex] = arr[rightIndex]
rightIndex += 1
tmpIndex += 1
while low <= mid:
tmpArray[tmpIndex] = arr[low]
low+=1
tmpIndex+=1
while rightIndex<=high:
tmpArray[tmpIndex]=arr[rightIndex]
tmpIndex+=1
rightIndex+=1
while begin <= high:
arr[begin] = tmpArray[begin]
begin += 1
if __name__=='__main__':
while True:
line = sys.stdin.readline()
if not line:
break
arr = [int(x) for x in line.strip().split(' ')]
arr.remove(arr[0])
# *******************************************************
# 递归合并排序
mergeSortR(arr)
# *******************************************************
# *******************************************************
# 非递归合并排序
# mergeSortNoR(arr)
# *******************************************************
i_index = -1
for i in arr:
i_index += 1
if i_index < len(arr) - 1:
print(str(i), end=' ')
else:
print(str(i))
Post Views:
712