Kevin Pratama
Kevin Pratama

Reputation: 3

Sorting a negative Arrays

So i want to sort an arrays that contain negative number. I have this in my method. When i run it with negative input , java.lang.negativeArray exception is out. here is the code:

protected int size;
protected int offset;

public CountSort2(int nilaiMax,int nilaiMin)
{
   this.size = nilaiMax-nilaiMin+1;
   this.offset=nilaiMin;
}

public void sort(int[] arrInput)
{
    int[] arrFrek = new int[size];
    for(int i=0;i<arrFrek.length;i++)
    {
        arrFrek[i]=0;
    }

    for(int i=0;i<arrInput.length;i++)
    {
        arrFrek[arrInput[i]-offset]+=1;
    }

    for(int i =1; i<arrFrek.length;i++)
    {
        arrFrek[i] = arrFrek[i]+arrFrek[i-1];
    }
    int[] newArrInput = new int[arrInput.length];
    for(int i=0;i<arrInput.length;i++)
    {
        newArrInput[i]=arrInput[i];
    }

    for(int i=0;i<newArrInput.length;i++)
    {
        arrInput[arrFrek[newArrInput[i]-offset]-1]=newArrInput[i];
        arrFrek[newArrInput[i]-offset]-=1;
    }
}

did I miss something ?

Upvotes: 0

Views: 87

Answers (2)

SMA
SMA

Reputation: 37023

Reason is you are passing negative index while creating the array. So consider your statement like:

int[] arrFrek = new int[size];

Where you defined size as

this.size = nilaiMax-nilaiMin+1;

So your nilaiMin > nilaiMax and hence you get negative array size exception. You can read about the exception from javadoc here

Als note, if say your arrInput[i] is 0 and offset is 2, you are trying to access aray with index -2 which is why you will get array index out of bound exception. Note that array index starts from 0 hence it can't be negative.

Upvotes: 1

TheLostMind
TheLostMind

Reputation: 36304

Yes, there is a place in your code which could potentially lead to this exception.

int[] arrFrek = new int[size];

From javadocs

NegativeArraySizeException
Thrown if an application tries to create an array with negative size.

Upvotes: 0

Related Questions