Bubble sort in python











up vote
1
down vote

favorite












I am quite new in Python and I am starting my journey with sorting algorithms, PEP8 and the Zen of Python. I would like to get some feedback about my BubbleSort algorithm which I wrote.
Also, is there a possibility to change the break statement to something else which will stop the loop?



def bubble_sort(structure):
"""
Bubble sort.

Description
----------
Performance cases:
Worst : O(n^2)
Average : O(n^2)
Best case : O(n)

Parameters
----------
structure : Mutable structure with comparable objects.

Returns
-------
structure : return sorted structure.

Examples
----------
>>> bubble_sort([7,1,2,6,4,2,3])
[1, 2, 2, 3, 4, 6, 7]

>>> bubble_sort(['a', 'c', 'b'])
['a', 'b', 'c']

"""

length = len(structure)

while True:
changed = False
for i in range(length - 1):
if structure[i] > structure[i + 1]:
structure[i], structure[i + 1] = structure[i + 1], structure[i]
changed = True
if not changed:
break
return structure









share|improve this question









New contributor




Michael Ogorkovyi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • You can implement it with 2 for loops, then you can get rid of the break
    – RobAu
    11 hours ago












  • I get an idea now what if i change the break statment to return structure and delete the last line return structure. Will it harmonize with PEP8?
    – Michael Ogorkovyi
    11 hours ago












  • Welcome to Code Review. This Python block is invalid, since the doc string isn't indented. Please edit your post to fix the indentation and make sure that it reflects the one in your original code.
    – Zeta
    11 hours ago










  • Accidentally, i would like to ask one more question. Is there a more PythonicWay to write bubble sort algorithm. For example in this code I think PythonicWay is used in the replacement expression. Of course i would like to make the code redable for other users in the future. @Zeta i fixed indets. Thank you for advice.
    – Michael Ogorkovyi
    11 hours ago

















up vote
1
down vote

favorite












I am quite new in Python and I am starting my journey with sorting algorithms, PEP8 and the Zen of Python. I would like to get some feedback about my BubbleSort algorithm which I wrote.
Also, is there a possibility to change the break statement to something else which will stop the loop?



def bubble_sort(structure):
"""
Bubble sort.

Description
----------
Performance cases:
Worst : O(n^2)
Average : O(n^2)
Best case : O(n)

Parameters
----------
structure : Mutable structure with comparable objects.

Returns
-------
structure : return sorted structure.

Examples
----------
>>> bubble_sort([7,1,2,6,4,2,3])
[1, 2, 2, 3, 4, 6, 7]

>>> bubble_sort(['a', 'c', 'b'])
['a', 'b', 'c']

"""

length = len(structure)

while True:
changed = False
for i in range(length - 1):
if structure[i] > structure[i + 1]:
structure[i], structure[i + 1] = structure[i + 1], structure[i]
changed = True
if not changed:
break
return structure









share|improve this question









New contributor




Michael Ogorkovyi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • You can implement it with 2 for loops, then you can get rid of the break
    – RobAu
    11 hours ago












  • I get an idea now what if i change the break statment to return structure and delete the last line return structure. Will it harmonize with PEP8?
    – Michael Ogorkovyi
    11 hours ago












  • Welcome to Code Review. This Python block is invalid, since the doc string isn't indented. Please edit your post to fix the indentation and make sure that it reflects the one in your original code.
    – Zeta
    11 hours ago










  • Accidentally, i would like to ask one more question. Is there a more PythonicWay to write bubble sort algorithm. For example in this code I think PythonicWay is used in the replacement expression. Of course i would like to make the code redable for other users in the future. @Zeta i fixed indets. Thank you for advice.
    – Michael Ogorkovyi
    11 hours ago















up vote
1
down vote

favorite









up vote
1
down vote

favorite











I am quite new in Python and I am starting my journey with sorting algorithms, PEP8 and the Zen of Python. I would like to get some feedback about my BubbleSort algorithm which I wrote.
Also, is there a possibility to change the break statement to something else which will stop the loop?



def bubble_sort(structure):
"""
Bubble sort.

Description
----------
Performance cases:
Worst : O(n^2)
Average : O(n^2)
Best case : O(n)

Parameters
----------
structure : Mutable structure with comparable objects.

Returns
-------
structure : return sorted structure.

Examples
----------
>>> bubble_sort([7,1,2,6,4,2,3])
[1, 2, 2, 3, 4, 6, 7]

>>> bubble_sort(['a', 'c', 'b'])
['a', 'b', 'c']

"""

length = len(structure)

while True:
changed = False
for i in range(length - 1):
if structure[i] > structure[i + 1]:
structure[i], structure[i + 1] = structure[i + 1], structure[i]
changed = True
if not changed:
break
return structure









share|improve this question









New contributor




Michael Ogorkovyi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











I am quite new in Python and I am starting my journey with sorting algorithms, PEP8 and the Zen of Python. I would like to get some feedback about my BubbleSort algorithm which I wrote.
Also, is there a possibility to change the break statement to something else which will stop the loop?



def bubble_sort(structure):
"""
Bubble sort.

Description
----------
Performance cases:
Worst : O(n^2)
Average : O(n^2)
Best case : O(n)

Parameters
----------
structure : Mutable structure with comparable objects.

Returns
-------
structure : return sorted structure.

Examples
----------
>>> bubble_sort([7,1,2,6,4,2,3])
[1, 2, 2, 3, 4, 6, 7]

>>> bubble_sort(['a', 'c', 'b'])
['a', 'b', 'c']

"""

length = len(structure)

while True:
changed = False
for i in range(length - 1):
if structure[i] > structure[i + 1]:
structure[i], structure[i + 1] = structure[i + 1], structure[i]
changed = True
if not changed:
break
return structure






python






share|improve this question









New contributor




Michael Ogorkovyi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Michael Ogorkovyi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 10 hours ago









Null

1,1392921




1,1392921






New contributor




Michael Ogorkovyi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 11 hours ago









Michael Ogorkovyi

163




163




New contributor




Michael Ogorkovyi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Michael Ogorkovyi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Michael Ogorkovyi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • You can implement it with 2 for loops, then you can get rid of the break
    – RobAu
    11 hours ago












  • I get an idea now what if i change the break statment to return structure and delete the last line return structure. Will it harmonize with PEP8?
    – Michael Ogorkovyi
    11 hours ago












  • Welcome to Code Review. This Python block is invalid, since the doc string isn't indented. Please edit your post to fix the indentation and make sure that it reflects the one in your original code.
    – Zeta
    11 hours ago










  • Accidentally, i would like to ask one more question. Is there a more PythonicWay to write bubble sort algorithm. For example in this code I think PythonicWay is used in the replacement expression. Of course i would like to make the code redable for other users in the future. @Zeta i fixed indets. Thank you for advice.
    – Michael Ogorkovyi
    11 hours ago




















  • You can implement it with 2 for loops, then you can get rid of the break
    – RobAu
    11 hours ago












  • I get an idea now what if i change the break statment to return structure and delete the last line return structure. Will it harmonize with PEP8?
    – Michael Ogorkovyi
    11 hours ago












  • Welcome to Code Review. This Python block is invalid, since the doc string isn't indented. Please edit your post to fix the indentation and make sure that it reflects the one in your original code.
    – Zeta
    11 hours ago










  • Accidentally, i would like to ask one more question. Is there a more PythonicWay to write bubble sort algorithm. For example in this code I think PythonicWay is used in the replacement expression. Of course i would like to make the code redable for other users in the future. @Zeta i fixed indets. Thank you for advice.
    – Michael Ogorkovyi
    11 hours ago


















You can implement it with 2 for loops, then you can get rid of the break
– RobAu
11 hours ago






You can implement it with 2 for loops, then you can get rid of the break
– RobAu
11 hours ago














I get an idea now what if i change the break statment to return structure and delete the last line return structure. Will it harmonize with PEP8?
– Michael Ogorkovyi
11 hours ago






I get an idea now what if i change the break statment to return structure and delete the last line return structure. Will it harmonize with PEP8?
– Michael Ogorkovyi
11 hours ago














Welcome to Code Review. This Python block is invalid, since the doc string isn't indented. Please edit your post to fix the indentation and make sure that it reflects the one in your original code.
– Zeta
11 hours ago




Welcome to Code Review. This Python block is invalid, since the doc string isn't indented. Please edit your post to fix the indentation and make sure that it reflects the one in your original code.
– Zeta
11 hours ago












Accidentally, i would like to ask one more question. Is there a more PythonicWay to write bubble sort algorithm. For example in this code I think PythonicWay is used in the replacement expression. Of course i would like to make the code redable for other users in the future. @Zeta i fixed indets. Thank you for advice.
– Michael Ogorkovyi
11 hours ago






Accidentally, i would like to ask one more question. Is there a more PythonicWay to write bubble sort algorithm. For example in this code I think PythonicWay is used in the replacement expression. Of course i would like to make the code redable for other users in the future. @Zeta i fixed indets. Thank you for advice.
– Michael Ogorkovyi
11 hours ago












1 Answer
1






active

oldest

votes

















up vote
0
down vote













Your code looks nice and the documentation is high quality.



Maybe a few things can be improved anyway.



API



It could be a good idea to get inspiration from the Python API functions related to sorting, we have:





  • sorted returning a new list from an iterable


  • list.sort sorts a list in place, returns None


In your case, as structure is sorted in place, I am not sure it makes sense to return it.



Parameter structure



This is mostly personal opinion but instead of structure, I'd find container to be a better name.



Also, if you want to be precise in the documentation, you might want to say that it is mutable but also that it implements __len__, __getitem__ and __setitem__. These objects are also called (mutable) sequences.



The code



Not much to say about the code itself.



Instead of having if not changed: break, you could write a: while changed loop which is very slightly more concise.



Also, you'll find an optimisation suggestion on Wikipedia:




The bubble sort algorithm can be easily optimized by observing that the n-th pass finds the n-th largest element and puts it into its final place. So, the inner loop can avoid looking at the last n − 1 items when running for the n-th time




Before getting into such a change, I highly recommend writing unit tests.






share|improve this answer





















  • I have one more question. How can i make a copy of the structure to return it as sorted does ?
    – Michael Ogorkovyi
    9 hours ago










  • Changing the struct in place is fine to me. However, if you need, you could use the copy module. Alternatively, you could just also just call list to copy your container as a list.
    – Josay
    8 hours ago











Your Answer





StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");

StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});






Michael Ogorkovyi is a new contributor. Be nice, and check out our Code of Conduct.










draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f209361%2fbubble-sort-in-python%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
0
down vote













Your code looks nice and the documentation is high quality.



Maybe a few things can be improved anyway.



API



It could be a good idea to get inspiration from the Python API functions related to sorting, we have:





  • sorted returning a new list from an iterable


  • list.sort sorts a list in place, returns None


In your case, as structure is sorted in place, I am not sure it makes sense to return it.



Parameter structure



This is mostly personal opinion but instead of structure, I'd find container to be a better name.



Also, if you want to be precise in the documentation, you might want to say that it is mutable but also that it implements __len__, __getitem__ and __setitem__. These objects are also called (mutable) sequences.



The code



Not much to say about the code itself.



Instead of having if not changed: break, you could write a: while changed loop which is very slightly more concise.



Also, you'll find an optimisation suggestion on Wikipedia:




The bubble sort algorithm can be easily optimized by observing that the n-th pass finds the n-th largest element and puts it into its final place. So, the inner loop can avoid looking at the last n − 1 items when running for the n-th time




Before getting into such a change, I highly recommend writing unit tests.






share|improve this answer





















  • I have one more question. How can i make a copy of the structure to return it as sorted does ?
    – Michael Ogorkovyi
    9 hours ago










  • Changing the struct in place is fine to me. However, if you need, you could use the copy module. Alternatively, you could just also just call list to copy your container as a list.
    – Josay
    8 hours ago















up vote
0
down vote













Your code looks nice and the documentation is high quality.



Maybe a few things can be improved anyway.



API



It could be a good idea to get inspiration from the Python API functions related to sorting, we have:





  • sorted returning a new list from an iterable


  • list.sort sorts a list in place, returns None


In your case, as structure is sorted in place, I am not sure it makes sense to return it.



Parameter structure



This is mostly personal opinion but instead of structure, I'd find container to be a better name.



Also, if you want to be precise in the documentation, you might want to say that it is mutable but also that it implements __len__, __getitem__ and __setitem__. These objects are also called (mutable) sequences.



The code



Not much to say about the code itself.



Instead of having if not changed: break, you could write a: while changed loop which is very slightly more concise.



Also, you'll find an optimisation suggestion on Wikipedia:




The bubble sort algorithm can be easily optimized by observing that the n-th pass finds the n-th largest element and puts it into its final place. So, the inner loop can avoid looking at the last n − 1 items when running for the n-th time




Before getting into such a change, I highly recommend writing unit tests.






share|improve this answer





















  • I have one more question. How can i make a copy of the structure to return it as sorted does ?
    – Michael Ogorkovyi
    9 hours ago










  • Changing the struct in place is fine to me. However, if you need, you could use the copy module. Alternatively, you could just also just call list to copy your container as a list.
    – Josay
    8 hours ago













up vote
0
down vote










up vote
0
down vote









Your code looks nice and the documentation is high quality.



Maybe a few things can be improved anyway.



API



It could be a good idea to get inspiration from the Python API functions related to sorting, we have:





  • sorted returning a new list from an iterable


  • list.sort sorts a list in place, returns None


In your case, as structure is sorted in place, I am not sure it makes sense to return it.



Parameter structure



This is mostly personal opinion but instead of structure, I'd find container to be a better name.



Also, if you want to be precise in the documentation, you might want to say that it is mutable but also that it implements __len__, __getitem__ and __setitem__. These objects are also called (mutable) sequences.



The code



Not much to say about the code itself.



Instead of having if not changed: break, you could write a: while changed loop which is very slightly more concise.



Also, you'll find an optimisation suggestion on Wikipedia:




The bubble sort algorithm can be easily optimized by observing that the n-th pass finds the n-th largest element and puts it into its final place. So, the inner loop can avoid looking at the last n − 1 items when running for the n-th time




Before getting into such a change, I highly recommend writing unit tests.






share|improve this answer












Your code looks nice and the documentation is high quality.



Maybe a few things can be improved anyway.



API



It could be a good idea to get inspiration from the Python API functions related to sorting, we have:





  • sorted returning a new list from an iterable


  • list.sort sorts a list in place, returns None


In your case, as structure is sorted in place, I am not sure it makes sense to return it.



Parameter structure



This is mostly personal opinion but instead of structure, I'd find container to be a better name.



Also, if you want to be precise in the documentation, you might want to say that it is mutable but also that it implements __len__, __getitem__ and __setitem__. These objects are also called (mutable) sequences.



The code



Not much to say about the code itself.



Instead of having if not changed: break, you could write a: while changed loop which is very slightly more concise.



Also, you'll find an optimisation suggestion on Wikipedia:




The bubble sort algorithm can be easily optimized by observing that the n-th pass finds the n-th largest element and puts it into its final place. So, the inner loop can avoid looking at the last n − 1 items when running for the n-th time




Before getting into such a change, I highly recommend writing unit tests.







share|improve this answer












share|improve this answer



share|improve this answer










answered 10 hours ago









Josay

24.6k13783




24.6k13783












  • I have one more question. How can i make a copy of the structure to return it as sorted does ?
    – Michael Ogorkovyi
    9 hours ago










  • Changing the struct in place is fine to me. However, if you need, you could use the copy module. Alternatively, you could just also just call list to copy your container as a list.
    – Josay
    8 hours ago


















  • I have one more question. How can i make a copy of the structure to return it as sorted does ?
    – Michael Ogorkovyi
    9 hours ago










  • Changing the struct in place is fine to me. However, if you need, you could use the copy module. Alternatively, you could just also just call list to copy your container as a list.
    – Josay
    8 hours ago
















I have one more question. How can i make a copy of the structure to return it as sorted does ?
– Michael Ogorkovyi
9 hours ago




I have one more question. How can i make a copy of the structure to return it as sorted does ?
– Michael Ogorkovyi
9 hours ago












Changing the struct in place is fine to me. However, if you need, you could use the copy module. Alternatively, you could just also just call list to copy your container as a list.
– Josay
8 hours ago




Changing the struct in place is fine to me. However, if you need, you could use the copy module. Alternatively, you could just also just call list to copy your container as a list.
– Josay
8 hours ago










Michael Ogorkovyi is a new contributor. Be nice, and check out our Code of Conduct.










draft saved

draft discarded


















Michael Ogorkovyi is a new contributor. Be nice, and check out our Code of Conduct.













Michael Ogorkovyi is a new contributor. Be nice, and check out our Code of Conduct.












Michael Ogorkovyi is a new contributor. Be nice, and check out our Code of Conduct.
















Thanks for contributing an answer to Code Review Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f209361%2fbubble-sort-in-python%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Mont Emei

Province de Neuquén

Journaliste