0

I'm working on a quickselect algorithm. I'm not entirely sure my algorithm is working correctly but I don't think that is relevant to the behavior i'm seeing.

I have a recursive algorithm with a conditional check to exit the algorithm with a return printing the final quickselect solution. The conditional is triggered but I kept getting None returned. So I added a print statement right before the return. The print statement prints the value but the return still returns None.

Heres my code. The conditional is on line 11:

#!/usr/bin/env python
from random import randint

def rSelect(arr, k, left=0, right=None):
    if right == None:
        right = len(arr)
    if right == 1:
        return arr[k]
    else:
        j = partition(a,left, right)
        if j == k:
            print "arr: %s" % arr
            print "j: %s" % j
            print "arr[j]: %s" % arr[j]
            return arr[j]
        if j > k:
            rSelect(arr, k, left, j)
        if j < k:
            rSelect(arr, k-j, j+1, right)


def partition(a, l, r):
    """ randomized pivot """

    p = randint(l,r-1)
    a[l], a[p] = a[p], a[l]
    i = l + 1
    for j in range(l+1, r):
        if a[j] < a[l]:
            a[j], a[i] = a[i], a[j]
            i += 1
    a[l], a[i-1] = a[i-1], a[l]

    return i-1


a = [ 5,4,3,2,1 ]
print rSelect(a, 1)
Solomon Bothwell
  • 1,004
  • 2
  • 12
  • 21
  • Also your script is not working correctly, I changed 2 to 16 in list and it gives wrong result. – Pratibha Mar 06 '17 at 02:00
  • 1
    Also see [here](http://stackoverflow.com/questions/23543485/python-recursive-function-executing-return-statement-incorrectly), [here](http://stackoverflow.com/questions/38882826/how-to-return-a-value-from-a-recursive-python-function), and many more. – TigerhawkT3 Mar 06 '17 at 02:03
  • Thanks TigerHawkT3. I see now whats going on. – Solomon Bothwell Mar 06 '17 at 02:04

0 Answers0