I've written a Bubble Sort algorithm in Java and I want a review on these:
- Performance improvements.
- Code conventions.
- Algorithm design improvements.
- Cleaner approaches.
I would highly appreciate if you can review based on the points above, and I would prefer if you can add more points on top if it if you find necessary.
Here's the code:
package com.hassanalthaf.sortingalgorithms;
public class BubbleSort {
private int temporary;
public int[] sort(int[] numbers) {
for (int mainIterations = 0; mainIterations < numbers.length; mainIterations++) {
int comparisonsCount = (numbers.length - mainIterations) - 1;
for (int comparisons = 1; comparisons < comparisonsCount; comparisons++) {
if (numbers[comparisons] > numbers[comparisons + 1]) {
this.temporary = numbers[comparisons];
numbers[comparisons] = numbers[comparisons + 1];
numbers[comparisons + 1] = this.temporary;
}
}
}
return numbers;
}
}
Here's my main class calling the BubbleSort sort method:
package com.hassanalthaf.sortingalgorithms;
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 20, 51, 12, 43, 2, 20};
BubbleSort bubbleSort = new BubbleSort();
numbers = bubbleSort.sort(numbers);
for (int iterations = 0; iterations < numbers.length; iterations++) {
System.out.println(numbers[iterations]);
}
}
}
This produces an output:
1
2
12
20
20
43
51