如果枢轴不是中期,那么quickselectg将如何采取不同的行动

时间:2013-10-08 12:30:26

标签: python list function indexing quickselect

好吧所以我开发了一个通用的quickselect函数,它用于查找列表的中位数。

k = len(aList)//2 and the list is aList = [1,2,3,4,5]

那么,如果每次在列表的第一项启动时,程序的行为方式会有何不同。我必须在中心吗?另外我应该在哪里启动time.clock()以查找函数的已用时间。这是代码

def quickSelect(aList, k)

   if len(aList)!=0:
   pivot=aList[(len(aList)//2)]
   smallerList = []
   for i in aList:
       if i<pivot:
            smallerList.append(i)
   largerList=[]
   for i in aList:
       if i>pivot:
            largerList.append(i)
   m=len(smallerList)
   count=len(aList)-len(smallerList)-len(largerList)
   if k >= m and k<m + count:
      return pivot
   elif m > k:
      return quickSelect(smallerList,k)
   else:
      return quickSelect(largerList, k - m - count)

1 个答案:

答案 0 :(得分:0)

我没有看到将枢轴放在开头有任何问题。但这只是初始化枢轴。枢轴的整个想法通常是找到中间元素。

请尝试这个计算时间:

import time

start_time = 0
aList = [1,2,3,4,5]
k = len(aList)//2  

def quickSelect(aList, k):
    start_time = time.time()
#     print "%10.6f"%start_time
#     pivot = aList[0]
    if len(aList) != 0:
        pivot = aList[(len(aList) // 2)]
        smallerList = []
        for i in aList:
            if i < pivot:
                smallerList.append(i)
                largerList = []
        for i in aList:
            if i > pivot:
                largerList.append(i)
        m = len(smallerList)
        count = len(aList) - len(smallerList) - len(largerList)
        if k >= m and k < m + count:
            print "Pivot", pivot
#             print "%10.6f"%time.time()
            print "time: ", time.time() -start_time
            return pivot
        elif m > k:
            return quickSelect(smallerList, k)
        else:
            return quickSelect(largerList, k - m - count)


quickSelect(aList, k)

在这种情况下,列表的时间变为零非常小。 如果我误解了你的问题,请告诉我。

<强>输出:

Pivot 3
time:  0.0