I've written a InsertionSort 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 InsertionSort {
private final int SECOND_NUMBER_INDEX = 1;
public int[] sort(int[] numbers) {
for (int iterations = this.SECOND_NUMBER_INDEX; iterations < numbers.length; iterations++) {
int currentNumber = numbers[iterations];
int newIndex = iterations;
for (int comparisons = iterations; comparisons > 0; comparisons--) {
if (currentNumber < numbers[comparisons - 1]) {
newIndex--;
numbers[comparisons] = numbers[comparisons - 1];
}
}
numbers[newIndex] = currentNumber;
}
return numbers;
}
}
Here's my main class calling the InsertionSort
sort method:
package com.hassanalthaf.sortingalgorithms;
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 20, 51, 12, 43, 2, 20};
InsertionSort insertionSort = new InsertionSort();
numbers = insertionSort.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