chopper draw lion4
chopper draw lion4

Reputation: 13487

Why is insertion sort not working?

Switching from Python to Java and decided to code an insertionsort method. I have written this in Python and tried to switch over the code one-to-one, it all seems good to go but it is not functioning correctly. I cut out all the other class methods/data fields to converse space and tried to limit this code only to that which is relevant to this question:

public class test1 {
    static final int NOT_FOUND = -1; // A constant

    // Attributes (just one)
    private double data[];

    // Constructor
        test1 (double data[]) {
            this.data = data.clone(); 
            }

        double getItem (int key) {
            return data[key];
        }

        void insertionSort () {
            for (int i = 1;i >= data.length;i++){
                double currentElement = data[i];
                int k = i - 1;
                while(k>=0 & data[k] > currentElement){
                    data[k+1] = data[k];
                    k -= 1;
                    data[k + 1] = currentElement;
                }
            }
        }

public static void main(String[] arg){
    double testData[] = {1,4,32,5,673,145,68,14,757};
    test1 b = new test1 (testData);

    b.insertionSort();
    //See how array has changed
    for (int i = 0; i < 9; i++) {
           System.out.print(b.getItem(i) + ", ");
        }
    }
}

Upvotes: 0

Views: 91

Answers (3)

darijan
darijan

Reputation: 9775

Change

for (int i = 1; i >= data.length; i++)

to

for (int i = 1; i < data.length; i++)

The reason behind it is that you are retrieving an item from the array data for the index of i. The loop did not work because i was initialized to 1 and the condition i >= data.length was returning false because i is actually smaller than the length of the data array in your example, hence the loop did not run.

There are other troubles with this kind of check in the for loop when retrieving an element from an array because if an index for which you are returning the element is >= than the length of the array you will get an IndexOutOfBoundsException.

Upvotes: 3

Roberto
Roberto

Reputation: 9080

I know that is not exactly what are you asking, but if you are learning Java, maybe you could find useful:

In Java you can use Arrays.sort() :

void insertionSort () {
  Arrays.sort(data);
}

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70931

I am sure this is not what you meant:

for (int i = 1;i >= data.length;i++){

This will be either an infinite(actually up to overflow) or an empty cycle.

Upvotes: 2

Related Questions