Search code examples
pythonsortingindexingdoubledirection

Why am I getting IndexError: list index out of range in this code?


Im trying to make a two way bubble sort. on odd iterations, it bubbles and sorts to the right, on even iterations, it bubbles and sorts to the left.

def main():

    myList = [10,9,8,7,6,5,4,3,2,1]
    lengthOfList = len(myList)
    firstThresh = 0
    lastThresh = lengthOfList
    oddPass = True
    while firstThresh <= lastThresh:
        if oddPass == True:
            for index in myList[firstThresh:lastThresh]:                
                if myList[index] > myList[index+1]:      <==================
                    temp = myList[index]
                    myList[index] = myList[index+1]
                    myList[index+1] = temp
                    print(myList)
                    oddPass = False
            lastThresh -= 1
        else:
            for index in reversed(myList[firstThresh:lastThresh]):
                if myList[index] < myList[index-1]:
                    temp = myList[index]
                    myList[index] = myList[index-1]
                    myList[index+1] = temp
                    print(myList)
                   oddPass = False
            firstThresh += 1
main()

The error: line 22, in bubbleSort2Way if myList[index] > myList[index+1]: IndexError: list index out of range

I put the arrow where the problem is. I am a beginner at programming so if its obvious im sorry! Any help would be great!


Solution

  • The line

    for index in myList[firstThresh:lastThresh]:
    

    is using the values from myList, not the index. So the code is trying to access the 11th element (index "10") on a list with only 10 elements and getting an out of range error.

    To use the index in your loop, change this line to

    for index, value in enumerate(myList[firstThresh:lastThresh]):