I've started trying to use python again for some simple code, where before I've only really used p5.js. I'm trying to code a bubble sort and after making a working bubble sort, I copied part of the code into another code to implement into First Fit decreasing bin packing. Now with minimal changes, the sort isn't working where it would before. I only changed it to perform all bubble sorts until it is sorted instead of once at a time with user input in between. The new code does not sort the items correctly and often sorts the highest number on the list into the middle. I tried this with numbers including 108 and 20 and 108 was always after 20 even though it's a decreasing sort. The bubble function I use is
def bubble(x):
y = []
i = 0
k = 1
while i + k < len(x):
if x[i] < x[i + k]:
y.append(x[i + k])
k = k + 1
else:
y.append(x[i])
i = i + k
k = 1
y.append(x[i])
return y
The original code is:
numbers = []
len = int(input("How many numbers are there? "))
for i in range(0, len):
current = str(i + 1)
num = int(input("Number " + current + " "))
numbers.append(num)
print("Here are your numbers:")
print(numbers)
bubbling = False
def bubble(x):
y = []
i = 0
k = 1
while i + k < len:
if x[i] < x[i + k]:
y.append(x[i + k])
k = k + 1
else:
y.append(x[i])
i = i + k
k = 1
y.append(x[i])
return y
cont = input("Bubble? (Y/N) ")
if cont == "Y":
bubbling = True
while bubbling == True:
previous = numbers
numbers = bubble(numbers)
if numbers == previous:
end = input("The bubble sort has been finished" )
bubbling = False
break
print(numbers)
cont = input("Bubble? (Y/N) ")
if cont == "Y":
continue
else:
break
and my second iteration is: (numbers are just input one at a time and enter nothing for it to bubble)
listing = True
bubbling = True
temp_array = []
# if an input is empty, stop adding numbers to the array and add bin size (LATER)
while listing:
temp_number = input()
if temp_number:
temp_array.append(temp_number)
else:
listing = False
break
print(temp_array)
def bubble(x):
y = []
i = 0
k = 1
while i + k < len(x):
if x[i] < x[i + k]:
y.append(x[i + k])
k = k + 1
else:
y.append(x[i])
i = i + k
k = 1
y.append(x[i])
return y
while bubbling:
prev_array = temp_array
temp_array = bubble(prev_array)
if temp_array == prev_array:
bubbling = False
break
print(temp_array)
bubble([108, 20])actually returns[20, 108], which it doesn't.temp_number = input()will give you a string. If you sort the strings'108'and'20', then'20' > '108', because strings are compared character by character, dictionary-style:'2' > '1', so'20'is bigger. You just needtemp_number = int(input())or something similar somewhere. If you understand that and it's just a simple oversight, we can close this question as a typo; if you need further explanation, we can find a duplicate with a detailed answer.bubble(x)tosorted(x)for a variety of differentxlists. If you just need some numbers sorted, just callsortedinstead of implementing your own less-efficient sort.