0

I've attempted to write an insertion sort and when looked up on the internet, I couldn't understand the code.

Here's what I did:

public class InsertionSort {
    public static void sort (int array[]) {
        for (int i = 1; i < array.length; i++) {
            int j = i - 1;
            while (j >= 0 && array [j] > array [j + 1]) {
                int temp = array [j + 1];
                array [j + 1] = array [j];
                array [j] = temp;
                j -= 1;
            }
        }
    }
}

Inside my main method, I wrote this:

public class TestAlgos {
    public static void main (String args []) {
        int array[] = {2,5,3,6,8,0,4,2,4,6,1,4,6,9,3};

        InsertionSort.sort(array);
        System.out.println(array);
    }
}

But when run, I got this output (I used eclipse by the way):

[I@ed17bee

Thus I searched online for solutions and found this code on a website.

while(i > 0 && Array[i] > key) {
    Array[i + 1] = Array[i];                
    i = i - 1;
}
Array[i + 1] = key;

I don't know whether my code is wrong. Please explain.

Also, my second question is why instead of error, a number-string thingy is displayed as output.

  • there are a lot of insertion sort variations. If your approach is *different* it doesn't mean it's worse. Are you getting the desired output with your algorithm? – Andrew Tobilko Sep 18 '18 at 15:51
  • 1
    Regarding your second question.. https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array – javaleryon Sep 18 '18 at 16:14

1 Answers1

1

There is nothing wrong with your code since it's a valid Insertion sort implementation. Still the second code you've quoted is a better approach just because it makes less insertions.

Main difference is as follows: Your algorithm switches values until there are no more operations available/required for the current index's value.

Quoted algorithm shifts down the indexes of the values until no more operations are available/required and then places the value stored in key variable under the current index.

dbl
  • 1,109
  • 9
  • 17