I saw in Wikipedia (the first under Optimizing bubble sort) a pseudo-code to bubble sort and I implemented it in Python.
I am posting my implementation here because I'm new to Python, and I'm looking mostly for programming in a more pythonic way.
def bubbleSort(array):
n = len(array)
swapped = True
while swapped:
swapped = False
for i in range(n - 1):
if array[i] > array[i + 1]:
array[i], array[i + 1] = array[i + 1], array[i]
swapped = True
n -= 1
return array
def main():
array = [1, 7, 4, 3, 2, 9, 8, 5, 6]
array = bubbleSort(array)
print(array)
if __name__ == '__main__':
main()
I'd love to know if there are any stuff that I can optimize (syntactic-wise), like the fact that I'm writing swapped = True
, and afterward changing it again, and again ... which thing annoys me.
3 Answers 3
Your bubbleSort
function both mutate the array in-place and return
it. This is unnecessary at best, error-prone at worse since a user could think that it return a new list.
So I would remove the return
statement and have the main
look like:
def main():
array = [1, 7, 4, 3, 2, 9, 8, 5, 6]
bubbleSort(array)
print(array)
Even better, as your main
is mostly a test of bubbleSort
, you could rename it as such and accept the array as parameter:
def test_bubble_sort(array):
print(array, end=' => ')
bubbleSort(array)
print(array)
if __name__ == '__main__':
test_bubble_sort([1, 7, 4, 3, 2, 9, 8, 5, 6])
test_bubble_sort([9, 8, 7, 6, 4, 5, 2, 3, 1])
Also a beginner but one thing I would like to point out is naming function, Style Guide for Python Code states:
Function Names
Function names should be lowercase, with words separated by underscores as necessary to improve readability.mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.
So, in your case write bubble_sort
instead of bubbleSort
.
like the fact that I'm writing swapped = True, and afterward changing it again, and again annoys me.
The truth is that you do not even need that swapped
variable as you can simplify your function and get rid of repeated and useless instructions related to it:
def bubble_sort(array):
n = len(array)
while n:
for i in range(n - 1):
if array[i] > array[i + 1]:
array[i], array[i + 1] = array[i + 1], array[i]
n -= 1
return array
def main():
array = [1, 7, 4, 3, 2, 9, 8, 5, 6]
array = bubble_sort(array)
print(array)
if __name__ == '__main__':
main()
-
2\$\begingroup\$ Now it works. But your
while
loop could just be afor
loop:for n in range(len(array), 0, -1)
. \$\endgroup\$Graipher– Graipher2017年10月16日 06:49:18 +00:00Commented Oct 16, 2017 at 6:49
Explore related questions
See similar questions with these tags.