Sort the odd

You have an array of numbers.
Your task is to sort ascending odd numbers but even numbers must be on their places.

Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.

Example

sortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]
Good Solution1:

import java.util.*;

public class Kata {

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

    // Sort the odd numbers only
    final int[] sortedOdd = Arrays.stream(array).filter(e -> e % 2 == 1).sorted().toArray();
    
    // Then merge them back into original array
    for (int j = 0, s = 0; j < array.length; j++) {
      if (array[j] % 2 == 1) array[j] = sortedOdd[s++];
    }
    
    return array;
  }
  
}

Good Solution2:

import java.util.PrimitiveIterator.OfInt;
import java.util.stream.IntStream;

public class Kata {
  public static int[] sortArray(int[] array) {
    OfInt sortedOdds = IntStream
        .of(array)
        .filter(i -> i % 2 == 1)
        .sorted()
        .iterator();

    return IntStream
        .of(array)
        .map(i -> i % 2 == 0 ? i : sortedOdds.nextInt())
        .toArray();  
      }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容