in case you're wondering, i'm not trying to simply sort an array with the lowest number first, i'm trying to sort an array by displaying the array list with the closest numbers to 0 first.
it works for some of the elements in the array but when it needs to go backwards through the array, it doesn't.. it just throws an out of bounds exception
here is my code:
package SSTF;
public class test2 {
public static void main (String[] args)
{
int[] temp_array = {9, 22, 3, -4, 5, 8};
for(int i =0; i<temp_array.length; i++)
{
System.out.print(temp_array[i] + " ");
}
System.out.println("\n\nNumbers closest to 0:\n");
closestToZero(temp_array);
}
public static void closestToZero(int[] array)
{
int num = array[0];
int absNum = Math.abs(num);
for(int i = 1; i < array.length; ++i)
{
int newAbs = Math.abs(array[i]);
if(newAbs < absNum)
{
absNum = newAbs;
num = array[i];
for(int j=0; j<array.length; j++)
{
System.out.print(array[i+j] + " ");
}
}
}
}
}
I really hope it is just something small and that someone can help, because I don't know how to fix it :S
output:
9 22 3 -4 5 8
Numbers closest to 0:
3 -4 5 8 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at SSTF.test2.closestToZero(test2.java:42)
at SSTF.test2.main(test2.java:18)