I just started studying algorithms and since I'm most familiar with Python decided to use it to actually put the algorithms I've been learning to use. How is my implementation of Bubble Sort? Does it make sense, is it efficient, too many variables, can you understand it without comments, any other tips for me?

Bubble sort algorithm.
import random
ls = []
max_length = 10
while len(ls) < max_length:
print ls
def bubble_sort(items_to_sort):
    right_item = -1 
    left_item = -2
    item_len = len(items_to_sort)
    number_of_passes = 0
    temp_item = 0
    max_checks = len(items_to_sort)
    if item_len > 1:
        while (number_of_passes < item_len) and (max_checks > 0):
            if items_to_sort[right_item] < items_to_sort[left_item]:
                temp_item = items_to_sort[right_item]  
                items_to_sort[right_item] = items_to_sort[left_item] 
                items_to_sort[left_item] = temp_item 
            right_item += -1
            left_item += -1
            number_of_passes += 1
            if left_item < -(item_len):
                right_item = -1
                left_item = -2
                number_of_passes = 0
                max_checks -= 1
    return items_to_sort    
print bubble_sort(ls)
  • \$\begingroup\$ Just found a bug in my code. Before the while statement I need to check if the length of the array is greater than 1 and if it is precede with my code and if not there is no need to sort so just return the list object. Will update my code to reflect the change. \$\endgroup\$ – terratunaz Oct 3 '16 at 21:28
  • \$\begingroup\$ See this answer for some ideas that might be helpful. \$\endgroup\$ – Gareth Rees Oct 3 '16 at 21:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.