Reputation: 27
I´m working on a simple bubble sort script. I've tried several test cases, but some of them doesn't order the numbers as expected. Here is my code with one test case that does not work.
def bubble_sort(array):
i = 0
j = 1
for x in range(0, len(array)):
for y in range(1000):
if(i == 4 and j == 5):
i, j = 0, 1
if(array[i] <= array[j]):
pass
if(array[i] > array[j]):
array[i], array[j] = array[j], array[i]
#print(array)
i, j = i + 1, j + 1
pass
pass
return(array)
I´m passing this list to the code
[7, 3, 1, 2, 3, 3, 10, 15, 2]
And the output is
[1, 2, 3, 3, 7, 3, 10, 15, 2]
I can´t find the mistake on the code, although I think is in the number and logic of the iterations. Hope someone can help me.
Upvotes: 0
Views: 96
Reputation: 106
Here is different version of your code.
def bubbleSort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
After this codes, you need to initialize(create) your array, then call your def like this; bubbleSort(arr)
after all this things you can print your array in for loop.
for i in range(len(arr)):
print(arr[i])
Upvotes: 0
Reputation: 104539
This is just a fixed up version of your code:
I don't understand why your loops use x
and y
as enumeration values in the for-loops, but then you use another pair of indices: i
and j
. The i
and j
don't seem needed.
if(i == 4 and j == 5)
- not needed. Is this just a debugging thing?
pass
is just a no-op. I don't think you need it.
It's spelled bubble
, not buble
It gets simple pretty fast:
def bubble_sort(array):
for x in range(0, len(array)):
for y in range(x+1, len(array)):
if(array[x] > array[y]):
array[x], array[y] = array[y], array[x]
return(array)
Upvotes: 1