Search code examples
pythonrecursionselection-sort

How to return value of number of swaps in Selection Sort recursive in python


The Code:

def selection(list, i, j, flag, swapNumber):
    
    size = len(list)
    if (i < size - 1):
        if (flag):
            j = i + 1;
            print(list)
            
        if (j < size):
            if (list[i] > list[j]):
              swapNumber +=1
              print(swapNumber)
              list[i],list[j]=list[j],list[i]
            
            print(list)
            selection(list, i, j + 1, 0, swapNumber);
            
        
        else:
            selection(list, i + 1, i+2, 1, swapNumber);
    return(swapNumber)       


      
swapNumber = 0
list = [6, 2, 3, 7, 1]
numSwap = selection(list, 0, 1, 1, swapNumber)
print(list)
print(numSwap)

So I'm trying to return the value of the swapNumber but when it prints it just says 1. I tried placing the return(swapNumber) somewhere else didn't seem to help. Anyone can help with this?


Solution

  • The swapNumber passed to function selection is by value other than by reference.

    One possible solution is declare it to be global:

    def selection(list, i, j, flag):
        global swapNumber
        size = len(list)
        if (i < size - 1):
            if (flag):
                j = i + 1;
                print(list)
                
            if (j < size):
                if (list[i] > list[j]):
                  swapNumber +=1
                  print(swapNumber)
                  list[i],list[j]=list[j],list[i]
                
                print(list)
                swapNumber = selection(list, i, j + 1, 0);
                
            
            else:
                swapNumber = selection(list, i + 1, i+2, 1);
        return(swapNumber)       
    
    
          
    swapNumber = 0
    list = [6, 2, 3, 7, 1]
    numSwap = selection(list, 0, 1, 1)
    print(list)
    print(numSwap)