Search code examples
pythonbubble-sortenumerate

get index and value of bubblesort python


I implemented a bubble sort for sorting a list of numbers, I tried to use enumerate to get the indices as well as the values, but for some reason in doesn't work. I expect something like [(index, value)], but the output can be different as well, as long I can see the index with the value part.
Result [(4, 25), (2, 30), (3, 31), (1, 33), (0,38)].
Hope there is a simple change for that.

def sortPercent(unsortedArr):
    n = len(unsortedArr)
    for i, percent in enumerate(range(n-1)):        
        for j, percent in enumerate(range(0, n-i-1)):        
            if unsortedArr[j] > unsortedArr[j + 1]:
                unsortedArr[j],unsortedArr[j+1] = unsortedArr[j+1], unsortedArr[j]
    return unsortedArr

if __name__ == "__main__":
    unsortedArr = [38, 33, 30, 31, 25]
    print(sortPercent(unsortedArr))

Solution

  • you have to use enumerate on unsorted arr

    def sortPercent(unsortedArr):
        unsortedArr = list(enumerate(unsortedArr)) # [(0, 38), (1, 33), (2, 30), (3, 31), (4, 25)]
        n = len(unsortedArr)
        for i, percent in enumerate(range(n-1)):        
            for j, percent in enumerate(range(0, n-i-1)):        
                if unsortedArr[j][1] > unsortedArr[j + 1][1]: # when j = 0, unsortedArr[j] = (0,38), unsortedArr[j][1] = 38, unsortedArr[j+1][1]=30
                    unsortedArr[j],unsortedArr[j+1] = unsortedArr[j+1], unsortedArr[j]
        return unsortedArr
    
    
    unsortedArr = [38, 33, 30, 31, 25]
    print(sortPercent(unsortedArr))
    # [(4, 25), (2, 30), (3, 31), (1, 33), (0, 38)]