Harry Alexander
Harry Alexander

Reputation: 35

How do you only order odd numbers in an int array and leave even numbers in their original position?

Basically, there is this challenge online where you have to order the odd numbers in an array in ascending order, while also ignoring the even numbers. So for example, [3,1,4,2,3,6] would be -> [1,3,4,2,3,6]. I've written an algorithm to sort the numbers, but the output is wrong.

import java.util.Arrays;

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

        int n;
        int temp = 0;
        if (array.length < 2){
            System.out.println(Arrays.toString(array));
            return array;
        }

        for (n = 1; n < array.length; n++) { // iterates through array
            if (array[n] % 2 != 0 && array[n] > array[n-1] && array[n-1] % 2 != 0){ // if n is odd and smaller than n-1 and n-1 is odd
                temp = array[n];
                array[n] = array[n-1];
                array[n-1] = temp;

            }
            else if (array[n] % 2 == 0 && array[n] < array[n-1]){
                array[n] = array[n];
            }
            else if (array[n] % 2 != 0 && array[n] > array[n-1]){
                array[n] = array[n];
            }

        }
        System.out.println(Arrays.toString(array));
        return array;

    }
}

Driver code

public class Driver {
    public static void main(String[] args) {

       Kata.sortArray(new int[]{3,1,11,2,9});
      
    }
}

for the array above, the output should be: [1,3,9,2,11] but instead it's [3, 11, 1, 2, 9]. I've been staring at this for ages and I'm stumped, honestly. Thanks a lot for reading!

Upvotes: 1

Views: 580

Answers (1)

Ralf Renz
Ralf Renz

Reputation: 1061

I used an inner loop to find the next odd number to sort. And I used an additional outer loop because normally sorting needs two loops.

import java.util.Arrays;

public class Kata {
public static int[] sortArray(int[] array) {
    int i;
    int n;
    int m;
    int temp = 0;
    if (array.length < 2) {
        System.out.println(Arrays.toString(array));
        return array;
    }

    for (i = 0; i < array.length; i++) {
        for (n = 0; n < array.length; n++) {
            if (array[n] % 2 != 0) {
                for (m = n + 1; m < array.length; m++) {
                    if (array[m] % 2 != 0) {
                        if (array[n] > array[m]) {
                            temp = array[n];
                            array[n] = array[m];
                            array[m] = temp;
                        }
                        break;
                    }
                }
            }
        }
    }
    System.out.println(Arrays.toString(array));
    return array;
}
}

Upvotes: 2

Related Questions