user10290452
user10290452

Reputation:

What is the comparison between these codes regarding Insertion Sort?

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.

Upvotes: 0

Views: 50

Answers (1)

dbl
dbl

Reputation: 1109

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.

Upvotes: 1

Related Questions