4
\$\begingroup\$

I have written the below bubble sort code in Python.

def bubble_sort():    num_list=[]    list_cnt=input("How many numbers you would like to sort:")    for i in range(int(list_cnt)): ### need to convert the value returned by input()        num_list.append(input("Enter " +str(i)+" number:")) ##here we are using append method of list    print("The values input are as follows:")    print(num_list)    print(len(num_list))    ### Below new line of code added to convert list to integer###    num_list=list(map(int,num_list))    ## with the above line the code is now working as expected##    max_index=len(num_list)-1 ## because list begins with 0    print("max_index is:",max_index)    for i in range(len(num_list)-1):        j=0        swapped=False        for j in range(len(num_list)-1):            if num_list[j] > num_list[j+1]:                num_list[j],num_list[j+1]=num_list[j+1],num_list[j]                print("Sorted when j=" +str(j)+ " and i=" + str(i)+ " is:\n ")                print(num_list)                swapped=True        if not swapped:            break    print("The sorted list is :")    print(num_list)    bubble_sort()
Peilonrayz's user avatar
Peilonrayz
44.6k7 gold badges80 silver badges158 bronze badges
askedApr 25, 2018 at 9:18
Amarja's user avatar
\$\endgroup\$
0

2 Answers2

4
\$\begingroup\$

Your code's quite good. I'd however change it in the following ways:

  1. Move the creation of the lits out of thebuble_sort.
  2. Remove theprints frombuble_sort.
  3. FollowPEP8.
  4. Changefor i in range(...) towhile True:.
  5. Use better variables.num_list toarray could do.
  6. Usestr.format, rather than string addition.
  7. Change the creation ofnum_list to use a list comprehension.
def bubble_sort(array):    while True:        swapped = False        for j in range(len(array)-1):            if array[j] > array[j+1]:                array[j], array[j+1] = array[j+1], array[j]                swapped = True        if not swapped:            breakif __name__ == '__main__':    amount = input("How many numbers you would like to sort:")    array = [        int(input("Enter {} number:".format(i)))        for i in range(int(amount))    ]    print("The values input are as follows: {}".format(array))    bubble_sort(array)    print("The sorted list is: {}".format(array))
answeredApr 25, 2018 at 12:15
Peilonrayz's user avatar
\$\endgroup\$
2
  • 6
    \$\begingroup\$I agree with everything except renamingnum_list toarray, since it is a list, not an array.numbers would probably be better, since it explains what it contains, and implies that it is a sequence without stating a concrete type.\$\endgroup\$CommentedApr 25, 2018 at 13:43
  • \$\begingroup\$@RaimundKrämer You could uselist however that shadowslist. They're also IIRC arrays with list interfaces, so it's simpler to call it a list. Also we're only using it for it's array interface. But yeahnumbers could work.\$\endgroup\$CommentedApr 25, 2018 at 13:45
3
\$\begingroup\$

The IO code is mixed with the logic code. I separated them. Also, I made a few other changes including removing useless comments (the code should speak for itself, your comments don't add much; if you need comments, that probably means you should simplify your code). I also converted the numbers as soon as they are input.

def bubble_sort(num_list):    for i in range(len(num_list)-1):        swapped = False                for j in range(len(num_list) - 1):            if num_list[j] > num_list[j+1]:                num_list[j], num_list[j+1] = num_list[j+1], num_list[j]                swapped = True                if not swapped:            returndef main():    num_list = []    num_items = int(input("How many numbers you would like to sort:"))        for i in range(num_items):        num_list.append(int(input("Enter " + str(i + 1) + "st number:")))        bubble_sort(num_list)    print("The sorted list is:")    print(num_list)if __name__ == '__main__':    main()
answeredApr 25, 2018 at 12:25
Solomon Ucko's user avatar
\$\endgroup\$
0

You mustlog in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.