为什么插入排序在排序列表上运行O(n ^ 2)?

时间:2018-02-07 10:43:59

标签: python algorithm sorting

我正在使用Python进行算法分析,简而言之,我遇到了我怀疑是一个问题。我需要分析排序数组上插入排序的运行时间,所以我有以下代码

def insertionSort(arr1):
  t1 = time.time();
  insertion_sort.sort(arr1)
  t2 = time.time();
  print (len(arr1));
  print (str(t2-t1));
...
print ('Insertion Sort Beginning');

for x in range(0,15):
  #Creates arrays of various sizes with integers from 0-100 randomly sprawled about. They are named after the power of 10 the size is
  toSort1 = [randint(0,100)] * randint(100000,10000000);
  #Presorts the array, insertion sort is faster for small inputs
  sorted_list = insertion_sort.sort(toSort1);
  ##################################
  insertionSort(sorted_list);

问题是输出是O(n ^ 2)!我是Python的新手,所以我认为这可能是我没有抓到的语义错误。 insertion_sort应该被认为是正确的,但可以进行审核here。如果它在定时时以相反的顺序排序,但它实际上被传递给同一个分拣机两次,则情况可能就是这种情况。怎么会这样?

这是输出的图形表示

enter image description here

1 个答案:

答案 0 :(得分:2)

我的程序获得了线性时间结果。 enter image description here

我添加了insert-sort的实现,并对此测试进行了如下代码的少量修改。

from random import randint
import time

def insertion_sort(arr):

    # Traverse through 1 to len(arr)
    for i in range(1, len(arr)):

        key = arr[i]

        # Move elements of arr[0..i-1], that are
        # greater than key, to one position ahead
        # of their current position
        j = i-1
        while j >=0 and key < arr[j] :
                arr[j+1] = arr[j]
                j -= 1
        arr[j+1] = key

def insertionSort(arr1):
  t1 = time.time();
  insertion_sort(arr1)
  t2 = time.time();
  print str(len(arr1)) + ", " +  str(t2-t1)


print ('Insertion Sort Beginning');

for x in range(0,15):
  #Creates arrays of various sizes with integers from 0-100 randomly sprawled about. They are named after the power of 10 the size is
  toSort1 = [randint(0,100)] * randint(100000,10000000);
  #Presorts the array, insertion sort is faster for small inputs
  sorted_list = sorted(toSort1);
  ##################################
  insertionSort(sorted_list);

希望它有所帮助!