please help. I need to optimize my Bubble Sort algorithm in order to get less total comparisons than the non-optimised bubbleSort. I managed to create just the 'Normal Bubble sort (only travels from left to right):
def bubbleSort(values):
n = len(values) - 1
swap = True
ncomp = 0 # My total comparisons counter
while swap:
swap = False
for i in range(n): # i = 0, 1, 2, ..., n-1
ncomp += 1
if values[i] > values[i+1]:
temp = values[i]
values[i] = values[i+1]
values[i+1] = temp
swap = True
return values, ncomp
So basically i dont know how to create an 'optimised bubbleSort', a bubbleSortPlus function in which bubbles travel in both directions: from left to right, immediately followed by a travel from right to left. In theory, in each pass the travel of the bubbles should be shortened (saving in a variable the position of the last swap in a travel, and make the next travel start at that position. I tried so hard but i'm just a python newbie, please help.
I guess it has been optimized... The naive Bubble sort does not include the swap
flag. So it will not return until finish all O(n^2) comparisons in any cases. But with swap
flag, the number of comparison will be almost linear if the input sequence has been "almost sorted".
Here's some skeleton code that shows how to scan the array forwards and backwards, while shrinking the list on each iteration.
values = 100,101,102,103,104,105
start = 0
stop = len(values)-1
while stop > start:
for i in range(start, stop):
print i, "compare", values[i], "with", values[i+1]
print "moved a large value to index", stop
print
stop = stop - 1
if stop == start:
break
for i in range(stop, start, -1):
print i, "compare", values[i], "with", values[i-1]
print "moved a small value to index", start
print
start = start + 1
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.