简体   繁体   中英

stable sorting using python bubble sort

So, I got my list of tuples to sort out by order of ints. What I'm missing is making the sort stable..

How can i make bubble sort stable? (keep order on similar items)

def bubble_sort_2nd_value(tuples_list):
    NEWLIST = []
    ITEM_MOVE = 0
    for i in tuples_list:
        NEWLIST.append(i)
    for i in range(len(NEWLIST)):
         for j in range(i+1, len(NEWLIST)):
             if(NEWLIST[j][1] < NEWLIST[i][1]):
                 ITEM_MOVE = 1
                 NEWLIST[j],NEWLIST[i] = NEWLIST[i],NEWLIST[j]

    if (ITEM_MOVE == 0):
        print(tuples_list)
    else:
        print(NEWLIST)

tuples_list =  [('h2', 8), ('h4', 30), ('h6', 7), ('h8', 54), ('h1', 72), ('h3', 8), ('h5', 7), ('h7', 15), ('h7', 24)]

bubble_sort_2nd_value(tuples_list)

tester resault which is expected and y resault comparison : Showing output from element 0 expected: [('h6', 7), ('h5', 7), ('h2', 8), ('h3', 8), ('h7', 15), ('h9', 24), ('h4', 30), ('h8', 54), ('h1', 72)] actual: [('h6', 7), ('h5', 7), ('h3', 8), ('h2', 8), ('h7', 15), ('h9', 24), ('h4', 30), ('h8', 54), ('h1', 72)] result_code bubble_14 wrong 1

notice the h2/3 mix... need to fix it.. that what i mean by not stable

The best thing you could do right now is to understand why it is switching those items. Print at every step what items are being changed. Then you might understand the behaviour.

So I had a go at it, you don't compare the current item with the next item in the list, you compare the current item with all the following items in the list. The changes I made bellow might give you the result you want.

def bubble_sort_2nd_value(tuples_list):
    NEWLIST = []
    ITEM_MOVE = 0
    for i in tuples_list:
        NEWLIST.append(i)
    for i in range(len(NEWLIST)):
         for j in range(len(NEWLIST)-1):
             k=j+1
             if(NEWLIST[j][1] > NEWLIST[k][1]):
                 ITEM_MOVE = 1
                 NEWLIST[j],NEWLIST[k] = NEWLIST[k],NEWLIST[j]

    if (ITEM_MOVE == 0):
        print(tuples_list)
    else:
        print(NEWLIST)

tuples_list =  [('h2', 8), ('h4', 30), ('h6', 7), ('h8', 54), ('h1', 72), ('h3', 8), ('h5', 7), ('h7', 15), ('h7', 24)]

bubble_sort_2nd_value(tuples_list)

So what you are doing is not 100% bubble sort. Try this and tell me if you need me to explain why yours is not working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM