Search code examples
pythonlistfunctionindexingquickselect

How would quickselectg act differently if pivot wasn't the middle term


Alright so I have developed a generic quickselect function and it is used to find the median of a list.

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

So how would the program act differently if pivot started at the first item of the list each time. Do I have to make it at the center? Also where should I start the time.clock() in order to find the elapsed time of the function. Here is the code

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)

Solution

  • I don't see any issue in placing the pivot at the beginning. But that would be just to initialize the pivot. The whole idea of pivot is normally to find the middle element.

    Please try this for your time calculation:

    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)
    

    In this case the time comes to be zero for your list is very small. Please let me know, if I misinterpreted your question.

    OUTPUT:

    Pivot 3
    time:  0.0