Reputation: 8477
In my Java code for a sort program (which uses my implementation of insertionsort algorithm to sort 100000 integers), I am trying to find out how many times the elements in the array are exchanged. I set this as a static variable since the sort() method is static.
However,sometime during the running of the program, I think the integer limit is crossed and the final count is shown as negative. There must be a way to correct this and get the numerically correct count, but I am unable to figure this out..Can you help?
public class InsertionSort {
private static int exchcount=0;
public static void exch(Comparable[] a, int i,int j){
Comparable temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static int exchangeCount(){
return exchcount;
}
public static void sort(Comparable[] a){
int N = a.length;
for(int i=0; i< N;i++){
for(int j=i; j>0 && less(a[j],a[j-1]); j--){
exch(a,j,j-1);
exchcount++;
}
}
}
...
public static void main(String[] args) {
Integer[] a = RandomNumberArrayGenerator.generate(100000);
sort(a);
System.out.println("number of exchanges="+ exchangeCount());
}
This gives
number of exchanges= -1799089211
Upvotes: 2
Views: 676
Reputation: 2939
Primitive type int
is signed, 32-bit value from -2,147,483,648 to 2,147,483,647 (inclusive). See java tutorial for this.
If your value after end is -1799089211 than it means that when your exchanges
reaches 2,147,483,647 it goes to -2,147,483,648, than -2,147,483,647 and so on... So you are (-2,147,483,648 + 1799089211 - 1)
over limit for primitive type int
. Of course, this situation assume that your counter has been overflowed just one time, but it should overflow more than one time.
Use long
data type and (just for sure) test overflow for counter.
Upvotes: 4
Reputation: 35557
use long
instead of int
. it is the simple answer.
Upvotes: 0
Reputation: 500327
The easiest is to turn the counter into a long
instead of int
. That'll enable you to count up to 9,223,372,036,854,775,807.
If every exch()
takes one CPU cycle, it will take about 100 years on a 3GHz computer for the long
counter to overflow.
Upvotes: 5
Reputation: 2633
Each time you increase it you can check if it is negative and if it is then set overflow to one. You can also use another integer to keep track of this. Perhaps set it to 0 afterwards. Do you would chance
exchcount++;
into
exchcount++;
if (exchcount<0) {
overflowcount++;
exchcount=0;
}
You can also use a long instead this will allow your program to use 64 instead of 32 bits.
This would require you to chance
private static int exchcount=0;
into
private static long exchcount=0;
This will allow you to count towards 2^63 instead of 2^31
Upvotes: 1