Actually the are some good algorithms out there that you could use.
Each have complexity based on the number of comparisons it does so if you want to improve your code and use less number of comparisons, making this faster at the same time you could take a look to this list:
- QuickSort O(nlog(n))
- Bubblesort O(n^2)
- cocktailsort ( bubble with some modifications) O(n^2)
- Selection sort O(n^2)
- MergeSort O(nlog(n))
- HeapSOrt O(nlog(n))
- InsertionSort O(n^2)
The one you are using is named "BubbleSort", so what is n ? N is the number of elements in your arrays.. and the O results is the amount of comparisons you have to do to get the collections order. So the better complexity is in the order of log. So algorithms like quicksort, merge, heap, are pretty cool if you want good performance, in my opinion the better in this list is the quicksort.
So how quicksort works?
Quicksort is based on the principle "divide and conquer", using recursion.
( As you know a recursion solution uses more memory than an normal solution )
This is how QuickSort algorithm.
- The first is to choose a pivot element. This could be in the middle, left o right of the array.
- Compare each element of the list with the pivot element and put the elements to right ( if they are higher than pivot ) or to the left ( otherwise condition ).
- As you know, now you have 2 lists, one at the left and other in the right. so all you have to do is call again the QuickSort function recursively over those 2 lists while its lists have more than one elements.
Here is more information about this algorithm
You should know that quicksort is not the best, mixing sort algorithm and using it in different range could improve you code to, but this quicksort itself is good enough.
( I know you dont want to sort, so you need to modify to algorithm to do you work instead of sorting, but still is the one that made less comparisons, hope this could help you )