Sorting. Can I code BubbleSort more efficiently? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Sorting. Can I code BubbleSort more efficiently?

I would like advice on how to code BubbleSort more efficiently. Especially, I would like to not use an extra integer (here called sortHelp) for swapping the entries in the array, if possible. Thank you. https://code.sololearn.com/caV0QB2RWsiB/?ref=app

9th Oct 2019, 10:05 AM
Daniel Senkbeil
1 Answer
+ 3
You are doing the most efficient thing here. You can get rid of the temporary int, if you are willing to change your array from `int[]` to `Integer[]`: Integer[] listToSort = {...} ... java.util.Collections.swap(java.util.Arrays.asList(listToSort), i, i+1); But then the `swap` function just does what you are doing so it's not more efficient, and it looks cluttered. You can also swap integers using the "XOR swap" (google it) but that isn't really more efficient either. So what you are doing is fine.
9th Oct 2019, 12:00 PM
Schindlabua
Schindlabua - avatar