Reputation: 97
I'm trying to do Bubble Sort in Python, without making functions, importing functions, etc.
I've gotten this so far, but now I'm stumped :p
array = [1, 42, 321, 44, 121, 61, 812, 71, 10, 11]
number = 1
ArrayIndex = 0
numchange = 0
TotalNumberofLoops = 10
OuterLoop = 0
InnerLoop = 0
while OuterLoop < TotalNumberofLoops:
InnerLoop = OuterLoop + 1
while InnerLoop < TotalNumberofLoops:
if array[OuterLoop] < array[InnerLoop]:
numchange = array[InnerLoop]
array[OuterLoop] = array[InnerLoop]
array[InnerLoop] = numchange
InnerLoop=InnerLoop + 1
print array
OuterLoop = OuterLoop + 1
This gives the following output:
[812, 42, 321, 44, 121, 61, 812, 71, 10, 11]
[812, 812, 321, 44, 121, 61, 812, 71, 10, 11]
[812, 812, 812, 44, 121, 61, 812, 71, 10, 11]
[812, 812, 812, 812, 121, 61, 812, 71, 10, 11]
[812, 812, 812, 812, 812, 61, 812, 71, 10, 11]
[812, 812, 812, 812, 812, 812, 812, 71, 10, 11]
[812, 812, 812, 812, 812, 812, 812, 71, 10, 11]
[812, 812, 812, 812, 812, 812, 812, 71, 10, 11]
[812, 812, 812, 812, 812, 812, 812, 71, 11, 11]
[812, 812, 812, 812, 812, 812, 812, 71, 11, 11]
Thanks for any solutions!
Upvotes: 0
Views: 1427
Reputation: 4830
How about
def bubble_sort(x):
# bubble sort with early termination - O(N) for nearly sorted
swapped = False
if len(x) > 1:
for i in range(len(x) - 1):
if x[i] > x[i + 1]:
swapped = True
x[i+1], x[i] = x[i], x[i+1]
if swapped:
return bubble_sort(x[0:-1])+[x[-1]]
return x
Upvotes: 1
Reputation: 4106
Try this:
array = [1, 42, 321, 44, 121, 61, 812, 71, 10, 11]
number = 1
ArrayIndex = 0
numchange = 0
TotalNumberofLoops = 10
OuterLoop = 0
InnerLoop = 0
while OuterLoop < TotalNumberofLoops:
InnerLoop = OuterLoop + 1
while InnerLoop < TotalNumberofLoops:
if array[OuterLoop] < array[InnerLoop]:
array[OuterLoop], array[InnerLoop] = array[InnerLoop], array[OuterLoop]
InnerLoop = InnerLoop + 1
print(array)
OuterLoop = OuterLoop + 1
This way the swap of elements is more pythonic and also correct.
Upvotes: 1