I am trying to come up with a solution to sort only the odd numbers in an Array while keeping the even numbers intact. In order to accomplish that, I tried to remove all the odd numbers in the given array into a new array(odd_arr) and to fill that voids I inserted a large number(9731) so that I get to know where I should insert back the odd numbers once those odd numbers are sorted.
(Just for the sake of Understanding Ex: If array is {5,3,2,8,1,4} then step1: odd_arr will be {5,3,1} and array is {9731,9731,2,8,9731,4} step2: sorted odd_arr will be {1,3,5} step3: finally after substituting sorted odd numbers for the number '9731' in the main array, output should be array is {1,3,2,8,5,4}).
Here's my code which gives ArrayIndexOutOfBoundException :
class Test {
public static int[] sortArray(int[] array) {
int[] odd_arr = new int[50];
int k =0;
for(int i :array){
if(array[i] % 2 == 1)//Exception producing at this line{
odd_arr[k] = array[i];
array[i] = 9731;
k = k+1;
}
}
Arrays.sort(odd_arr);
int j=0;
for(int i:array){
if(array[i] == 9731){
array[i] = odd_arr[j];
j = j+1;
}
}
return array;
}
public static void main(String[] args) {
int[] array = {5, 3, 2, 8, 1, 4};
int[] sorted_array = sortArray(array); //Exception here too
for(int i=0; i<sorted_array.length;i++)
System.out.print(sorted_array[i] + " ");
}
}