Hi I reviewed other posts with bubble sort, but solution didn't work in my case: So algorithm works until I repeat few times while loop. But how can I do this without using input? Here is my code so you know what I mean:
x = [0, 0, 1, 3, 3, 2, 2, 1, 0, 4, 5]
h = None
flag = True
while flag == True:
#flag = True
for i in range(len(x) - 1):
if x[i] > x[i + 1]:
# flag = False
h = x[i]
x[i] = x[i + 1]
x[i + 1] = h
print(x)
#input = raw_input('Satisfied? ')
#if input == 'q':
# break
print(x)
'''
we can replace variable h, with:
x[i] , x[i+1] = x[i+1], x[i]
'''
You can make use of the sorted
function in python, and change your code to be:
while flag == True:
for i in range(len(x) - 1):
if x[i] > x[i + 1]:
h = x[i]
x[i] = x[i + 1]
x[i + 1] = h
if sorted(x) == x: #x is already sorted
flag = False
Edit: Alternate solution which doesn't use python's built in sort function:
while flag == True:
flag = False
for i in range(len(x) - 1):
if x[i] > x[i + 1]:
flag = True
h = x[i]
x[i] = x[i + 1]
x[i + 1] = h
Hope I helped!
With this algorithm, you can previously know how many steps (max) are needed to sort the whole array, because the algorithm is convergent and bounded. In each pass, the highest no-placed value is placed correctly, so you will need n-1 passes to complete the sorting.
Here an example:
mylist = [54,26,93,17,77,31,44,55,20]
for num in range(len(mylist)-1, 0, -1):
for i in range(num):
if mylist[i] > mylist[i+1]:
aux = mylist[i]
mylist[i] = mylist[i+1]
mylist[i+1] = aux
print(mylist)
Hope it helps
PS: What you intended to do, stopping when the list is sorted before the n-1 pass, is better done with the "insertion algorithm". Here there is an interesting comparision between insertion and bubble sorting: Insertion sort vs Bubble Sort Algorithms
I little refactor for your code:
for num in range(len(mylist)-1, 0, -1):
for i in range(num):
if mylist[i] > mylist[i+1]:
mylist[i], mylist[i+1] = mylist[i+1], mylist[i]
Python recursive bubble sort
def bubble_f(lst):
if len(lst) < 2:
return lst
if lst[0] > lst[1]:
return [lst[1]] + bubble_f([lst[0]] + lst[2:])
return [lst[0]] + bubble_f([lst[1]] + lst[2:])
def bubble_sort(lst):
if len(lst) < 2:
return lst
sorted = bubble_f(lst)
return bubble_sort(sorted[:-1]) + [sorted[-1]]
list1 = [5, 9, 23, 4, 3, 8, 1, 12, 2, 9, 15, 19, 11, 27, 0]
print(bubble_sort(list1))
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.