Interviewstreet的插入排序程序

时间:2013-01-12 13:11:52

标签: python insertion-sort

我尝试编写Interiewstreet的插入排序挑战Link for the challenge 在Python中,这是我的代码,如下所示。

程序对输入元素的限制(我不确定)运行正常,但对于较大尺寸的输入返回错误输出。谁能指导我,我做错了什么?

# This program tries to identify number of times swapping is done to sort the input array 

"""
=>Get input values and print them
=>Get number of test cases and get inputs for those test cases
=>Complete Insertion sort routine
=>Add a variable to count the swapping's 
"""

def sort_swap_times(nums):
  """ This function takes a list of elements and then returns the number of times 
      swapping was necessary to complete the sorting
  """

  times_swapped = 0L
  # perform the insertion sort routine
  for j in range(1, len(nums)):
    key = nums[j]
    i = j - 1
    while i >= 0 and nums[i] > key:
      # perform swap and update the tracker
      nums[i + 1] = nums[i]
      times_swapped += 1
      i = i - 1
    # place the key value in the position identified
    nums[i + 1] = key

  return times_swapped


# get the upper limit.
limit = int(raw_input())  
swap_count = []

# get the length and elements.
for i in range(limit):
  length = int(raw_input())
  elements_str = raw_input() # returns a list of strings

  # convert the given elements from str to int
  elements_int = map(int, elements_str.split())

  # pass integer elements list to perform the sorting
  # get the number of times swapping was needed and append the return value to swap_count list
  swap_count.append(sort_swap_times(elements_int))


# print the swap counts for each input array
for x in swap_count:
  print x

1 个答案:

答案 0 :(得分:2)

您的算法是正确的,但这是一个天真的问题解决方法,并会在大型测试用例(即len(nums)> 10000)上为您提供超时限制信号。让我们分析算法的运行时复杂性。

for j in range(1, len(nums)):
    key = nums[j]
    i = j - 1
    while i >= 0 and nums[i] > key:
      # perform swap and update the tracker
      nums[i + 1] = nums[i]
      times_swapped += 1
      i = i - 1
    # place the key value in the position identified
    nums[i + 1] = key

上述代码段所需的步数与1 + 2 + .. + len(nums)-1或len(nums)*(len(nums)-1)/ 2步进行比较,即O (LEN(NUMS)^ 2)。

<强>提示

使用所有值都在[1,10 ^ 6]范围内的事实。你在这里真正做的是找到列表中的反转次数,即找到所有i&lt; j s.t. nums [i]&gt; NUMS [J]。考虑一种数据结构,它允许您以对数时间复杂度查找每个插入操作所需的交换次数。当然,还有其他方法。

<强>扰流

  

Binary Indexed Trees