+ 5
Bubble sort algorithm. What’s wrong in it
What’s wrong in this code. It’s just sorting the highest value def bubsort(llists): length = len(llists) -1 for i in range(length): while True: if not llists[i] < llists[i + 1] and llists[i] != llists[i + 1] : llists[i], llists[i + 1] = llists[i + 1], llists[i ] else: break print(llists) wow = [82,1,-352,0,272,3.2,5.3,82,9] bubsort(wow) https://code.sololearn.com/cny9oXPBPRrC/?ref=app
9 Answers
+ 2
You are done for single round which puts max value at last
You need to repeat this for more range(length)-1 of times...
+ 2
def bubsort(llists):
length = len(llists) -1
for j in range(length): # this needed there
for i in range(length):
if llists[i] > llists[i + 1] :
llists[i], llists[i + 1] = llists[i + 1], llists[i]
print(llists)
wow = [82,1,-352,0,272,3.2,5.3,82,9]
bubsort(wow)
"""
your code works for single iterations, so according to algorithm which only send single max value to end. For nextsx to put in last but ond position and to reapeat this till all in sort, you need one more outer loop
And your while is no need there it works for 2 iteration and in second iteration it breaks so you can just use a if block.
See my changes...
your condition and while loop works fine but you have redundant instructions. you can simplify it.
Hope it helps...
"""
+ 1
UMAR FAROOQ what answer do you need still?
+ 1
"""Yes. The above works same as you expected for bubble sort algorithm except breaking when no swaps..
I added break also here, see this code:"""
def bubsort(llists):
length = len(llists) -1
for j in range(length): # this needed there
swap=False
for i in range(length):
if llists[i] > llists[i + 1] :
llists[i], llists[i + 1] = llists[i + 1], llists[i]
swap=True
print(llists, "swaped:" , swap) #test
if not swap: break
wow = [3,1,5,2]
bubsort(wow)
+ 1
UMAR FAROOQ bubble sort is my favorite sorting algorithm that I had learnt in my early College days.
To give you a hint :
temp = a
a = b
b = temp
This will swap two values based on some condition a > b OR a < b
0
Isnt the for loop repeating it for every element in list?
0
Im kinda confused with nested loops
0
Can someone answer it please
0
I want it to work for all values but in this way:
Let's take the following array: [3, 1, 5, 2]
Step 1: [1, 3, 5, 2] - the first two elements are compared and swapped.
Step 2: [1, 3, 5, 2] - the next pair is compared and not swapped, as they are in order.
Step 3: [1, 3, 2, 5] - the last two elements are swapped.
This was the first iteration over the array. Now we need to start the second iteration:
Step 1: [1, 3, 2, 5]
Step 2: [1, 2, 3, 5]
Step 3: [1, 2, 3, 5]
The third iteration will not swap any elements, meaning that the list is sorted!
See this animation for more clarification(i want it to work exactly same):
https://code.sololearn.com/WoTIJF4t6uWv/?ref=app