\$\begingroup\$
\$\endgroup\$
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
asked Jun 25, 2016 at 8:11
1 Answer 1
\$\begingroup\$
\$\endgroup\$
0
- this code is not commented
strikingly, it does not even have doc comments - given at least two classes from the same coder that do essentially the same thing, there should be an 'interface' - look for one you can use (if as a template), especially from the Java API
SECOND_NUMBER_INDEX
is close to meaningless- as a "genuine" constant,
SECOND_NUMBER_INDEX
should be static int[] sort(int[] numbers)
would then not use any instance (data) members and should be a class/static method instead of an instance one- if
iterations
was calledordered
orsorted
, the condition of the outer loop read close to a loop invariant - having found the first element no bigger than
currentNumber
, continuing to index0
isn't called for - just placecurrentNumber
andbreak
the inner loop, no need fornewIndex
Use a foreach-loop in main()
.
answered Jun 25, 2016 at 10:31
lang-java