The code is not working for some test cases.
def bubbleSort(array):
l = 0
r = 1
isSorted = False
while not isSorted:
isSorted = True
while r <= len(array)-1:
if array[r] < array[l]:
swap(l, r, array)
isSorted = False
l += 1
r += 1
return array
def swap(i, j, array):
array[i], array[j] = array[j], array[i]
return
Can anyone help me resolve this issue??
You need to reinitialize r and l back to r = 1
and l = 0
inside while not isSorted:
. Otherwise you would only be running the complete loop once since at the end of first iteration, r is already at len(array)
As far as your code is concerned you have to loop through all the elements every time isSorted
is False
. So, you have to initialize l = 0
and r = 1
every time when outer while
loop executes.
There is no need to use two counter variables l
& r
, you can simply implement bubble sort as follows:
def bubbleSort(array):
isSorted = False
while not isSorted:
isSorted = True
for i in range(1, len(array)):
if array[i] < array[i - 1]:
swap(i, i - 1, array)
isSorted = False
return array
def swap(i, j, array):
array[i], array[j] = array[j], array[i]
return
And when you executes >>>print(bubbleSort([10, 2, 1, 3, 2, 6, 25]))
Output will be:
[1, 2, 2, 3, 6, 10, 25]
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.