-1

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] + " ");
 }
}
Harish
  • 127
  • 1
  • 1
  • 6
  • The code that you provided does not compile. Can you update your question? – Andrei Sfat Aug 12 '18 at 07:47
  • Array indexes are from 0 to array size -1 (0 to 5 in your example). Not the values of the array. – Guy Aug 12 '18 at 07:49
  • You're using the enhanced for-loop syntax `for (int i : array)` where you should have used a regular for-loop `for (int i = 0; i < array.size(); ++i)`. Review [this section in the Java Tutorials](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html) to learn the difference. – Kevin Anderson Aug 12 '18 at 07:50
  • It doesn't work because you use an enhanced for-loop (which returns the items of an array, **not indexes**) and use the returned item to get an item from the list. If your list contains `3, 6, 123`, it will crash on the first one because you use the first item of the list to query the list, and since there are only 3 items, you can only do array[2], not array[3] or higher – Zoe Aug 12 '18 at 08:01

2 Answers2

1

You are treating your for-each loops like regular loops,

for(int i : array){
    if(array[i] % 2 == 1)

should be

for(int i :array){
    if(i % 2 == 1)

But, I would actually break this up into a few methods to make it easier to reason about. Start with a method to count the odds. Like,

private static int countOdds(int[] array) {
    int count = 0;
    for (int val : array) {
        if (val % 2 != 0) {
            count++;
        }
    }
    return count;
}

In Java 8+ that could also be done like

private static int countOdds(int[] array) {
    return (int) Arrays.stream(array).filter(i -> i % 2 != 0).count();
}

Then, a method to copy the odd values to a new (temporary array), like

private static int[] copyOdds(int[] array) {
    int pos = 0;
    int[] odds = new int[countOdds(array)];
    for (int val : array) {
        if (val % 2 != 0) {
            odds[pos++] = val;
        }
    }
    return odds;
}

Or, in Java 8+,

private static int[] copyOdds(int[] array) {
    return Arrays.stream(array).filter(i -> i % 2 != 0).toArray();
}

And then your sortArray method practically writes itself. First, copy the odd values. Then sort them. Then copy them back into the original array. Like,

public static void sortOdds(int[] array) {
    int[] odds = copyOdds(array);
    Arrays.sort(odds);
    int pos = 0;
    for (int i = 0; i < array.length; i++) {
        if (array[i] % 2 != 0) {
            array[i] = odds[pos++];
        }
    }
}

And, to demonstrate, a main method

public static void main(String[] args) {
    int[] array = { 5, 3, 2, 8, 1, 4 };
    System.out.println(Arrays.toString(array));
    sortOdds(array);
    System.out.println(Arrays.toString(array));
}

Which outputs

[5, 3, 2, 8, 1, 4]
[1, 3, 2, 8, 5, 4]
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

First of all, try to use the correct indentation, that makes it easier to read.

When you use:

for (int i : array) {}

The variable 'i' will be the next that is in the array, so the first time it's 5, then 3, and so on. At one time it will be 8, and when you try to call array[8] on the array of length 6 it will return your error.

Instead of what you're doing, you should use:

class Test {

public static int[] sortArray(int[] array) {

int[] odd_arr = new int[50];
int k =0;


for(int i = 0; i < array.length; i++){
  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 = 0; i < array.length; i++) {
  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] + " ");
 }
}
Jack Jhonsen
  • 119
  • 6