1
\$\begingroup\$

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
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$
  • 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 called ordered or sorted, the condition of the outer loop read close to a loop invariant
  • having found the first element no bigger than currentNumber, continuing to index 0 isn't called for - just place currentNumber and break the inner loop, no need for newIndex

Use a foreach-loop in main().

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.