Home > Software design >  Sort odd numbers in Array of even and odd numbers
Sort odd numbers in Array of even and odd numbers

Time:07-13

I need to sort the odd numbers in the inputted array. So we do nothing with the even numbers in the array but we sort the odd numbers in ascending order

public static void main(String[] args) {
    System.out.println(sortArray(new int[]{1, 5, 2, 7, 3}));
}
public static int[] sortArray(int[] array) {
    List<Integer> odds = new ArrayList<>();
    for (int elmnt : array) {
        if (elmnt % 2 != 0) {
            odds.add(elmnt);
        }
    }
    odds.stream().sorted();
    for (int i = 0; i < array.length; i  ) {
        if (array[i] %2 != 0){
            for (int j = 0; j < odds.size(); j  ) {
                array[i] = odds.get(j);
            }
        }
    }
    return array;
}

in this example, the array should turn into: [1, 3, 2, 5, 7]

how can I do this?

CodePudding user response:

  • First, write a sort routine to sort normally in ascending order. If you don't know how to do that, you can do a web search for bubble sort, selection sort, etc. but the first two are easily implemented.
  • Once you have that working, simply modify the sort to work only on odd numbers.

It is not necessary to presort any or all of the array and then manipulate the values afterwards (although the cost of filtering and and sorting a smaller array in preparation may have performance benefits over sorting a larger array)

CodePudding user response:

Here is a nifty solution using the Stream API.

public static int[] sortOdds(int[] a) {
    var sortedOdds = Arrays.stream(a).filter(v -> v % 2 == 1).sorted().toArray();
    for (int i = 0, s = 0; i < a.length; i  ) {
        if (a[i] % 2 == 1) {
            a[i] = sortedOdds[s];
            s  ;
        }
    }
    return a; // A return here is kind of redundant but whatever.
}

However, as @Yunnosch mentioned, this really isnt a good question for stack overflow. This feels like a homework question, and if it is I doubt any professor would accept the solution above since it uses sorted() instead of actually implementing a sorting algorithm.

  • Related