#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2011
    Posts
    6
    Rep Power
    0

    [Homework] Is my teacher's code flawed?


    I have an assignment to do in which I have to perform insertion sort.
    Thankfully my teacher has given us an insertion sort method that we can work with on our own.
    Code:
    public static void insertionSort(int [] data)
    {
        for(int end = 1; end < data.length; end++)
        {
            int item = data[end];
            int i = end;
            while (i > 0 && item < data[i - 1])
            {
                data[i] = data[i - 1];
                i--;
            }
            data[i] = item;
        }
    }
    So I tried inputting this into eclipse, just to test it out and see how it works.
    But it doesn't seem to be working.
    When testing it out I filled the data variable with...
    Code:
    int [] data = {8,5,7,10,4};
    However this part right here doesn't seem to make much sense
    Code:
     while (i > 0 && item < data[i - 1])
    No matter what I input, the first number of int[] data seems to cause an infinite loop all the time.
    Am I doing something wrong here? Or was the method I was given flawed in some way? If so is there a way to fix it?
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    Hi,

    I don't know what you've tried, but this code is correct and works flawlessly.

    And that's no wonder, because this is an exact copy of the standard implementation used by probably every school, university and author on this planet.

    The idea is to put the current item into the already sorted first part of the array. Hence the check for item < data[i - 1]: "i" is the index where "item" should go. If "item" is still smaller than the element left of i, it is moved further to the left ("i" is decremented). When the correct position is reached, "item" is put on this position.
  4. #3
  5. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jan 2004
    Location
    Mobile, Alabama
    Posts
    4,022
    Rep Power
    1285
    Did you copy the code or retype it? If you retyped it, did you accidentally put a ; at the end of the while?
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    62
    Rep Power
    4
    Generally, lecturers code isn't always perfect, and nor should it be. Debugging is a vital skill to learn and one of the things that you'll actually need as a developer.

    Also consider that there's academically sound code and real-world code ;-)

    Regards,

    Shaun.

IMN logo majestic logo threadwatch logo seochat tools logo