Sort even numbers in ascending and odd numbers in descending order.

huangapple go评论55阅读模式
英文:

Sort even numbers in ascending and odd numbers in descending order

问题

给定一个数字数组,需要按照以下要求对偶数进行升序排序,奇数进行降序排序。输入是 {9,3,5,6,7,8},输出是 {6,8,9,7,5,3}

我尝试了,但我的输出中偶数以降序排列,奇数以升序排列。

我的代码:

package practice;
import java.util.*;

public class arrange
{
    static void twoWaySort(int arr[], int n)
    {
        for (int i = 0; i < n; i++)
            if ((arr[i] & 1) == 0) 
                arr[i] *= -1;
        Arrays.sort(arr);
        for (int i = 0; i < n; i++)
            if ((arr[i] & 1) == 0)
                arr[i] *= -1;
    }

    public static void main(String[] args)
    {
        int arr[] = { 9,3,5,6,7,8 };

        twoWaySort(arr, arr.length);

        System.out.println(Arrays.toString(arr));
    }
}
英文:

Given an array of numbers, need to sort even nos in ascending order and odd nos in descending order. Input is {9,3,5,6,7,8}, output is {6,8,9,7,5,3}.

I tried but in my output, even numbers gets arranged in descending order and odd numbers in ascending.

My Code:

package practice;
import java.util.*;

public class arrange
{
	static void twoWaySort(int arr[], int n)
	{
		for (int i = 0; i < n; i++)
			if ((arr[i] & 1) == 0) 
				arr[i] *= -1;
		Arrays.sort(arr);
		for (int i = 0; i < n; i++)
			if ((arr[i] & 1) == 0)
				arr[i] *= -1;
	}

	public static void main(String[] args)
	{
		int arr[] = { 9,3,5,6,7,8 };

		twoWaySort(arr, arr.length);

		System.out.println(Arrays.toString(arr));
	}
}

答案1

得分: 0

你可以将int[]转换为Integer数组,然后使用自定义的Comparator进行排序,首先按奇偶性排序,然后按实际值排序。

int[] res = Arrays.stream(arr).boxed().sorted(
             Comparator.comparingInt((Integer x) -> x & 1)
              .thenComparingInt(x -> (x & 1) == 0 ? x : -x)).mapToInt(x -> x).toArray();
// 如果需要原地修改,你也可以将res复制回arr
英文:

You could convert the int[] to an array of Integer, then sort it with a custom Comparator that first looks at parity, then the actual value.

int[] res = Arrays.stream(arr).boxed().sorted(
             Comparator.comparingInt((Integer x) -> x & 1)
              .thenComparingInt(x -> (x & 1) == 0 ? x : -x)).mapToInt(x -> x).toArray();
// you can also copy over res into arr if in-place modification is required

答案2

得分: 0

你有三种简单的选项来适应你的代码:

  1. 临时将奇数变为负数或
  2. 反转排序顺序
  3. 在最后翻转数组

但请注意,所有这些方法都会让奇数首先出现在结果中!

对于变体1,你需要在for循环内反转if条件:

for (int i = 0; i < n; i++) {
    if ((arr[i] & 1) != 0) {
        arr[i] *= -1;
    }
}

对于变体2,你需要在sort方法中指定一个Comparator

Arrays.sort(arr, Comparator.reverseOrder());

请注意,对于这个变体,你需要使用Integer数组,因为sort方法只接受对象数组的Comparator。不用担心计算,自动装箱和拆箱会在必要的地方将int转换为Integer,反之亦然。

对于变体3,你只需要添加代码来翻转整个结果:

for (int i = 0; i < n / 2; i++) {
    int temp = arr[i];
    arr[i] = arr[n - i - 1];
    arr[n - i - 1] = temp;
}

总的来说,你应该始终使用大括号({})来增加代码的可读性,以及在声明数组时使用Java风格,即int[] arr,而不是int arr[](尽管两种风格都可以工作)。这是因为int[]是一个类,而int是一个原始类型,如果[]紧挨在基本类型旁边,你可以更清楚地看到这一点。

如果你不将数组的长度作为第二个参数传递,而是在方法内部使用arr.length,那么你的方法twoWaySort会更加健壮。

英文:

You have three easy options for your code to adapt:

  1. make the odd numbers negative temporarily or
  2. invert the sort order
  3. flip the array at the end

But please note that all methods shown here will let the odd numbers come first in the result!

For variant 1, you have to invert the if condition inside your for loops:

for (int i = 0; i &lt; n; i++) {
    if ((arr[i] &amp; 1) != 0) {
        arr[i] *= -1;
    }
}

For variant 2, you have to specify a Comparator in the sort method:

Arrays.sort(arr, Comparator.reverseOrder());

Please note that for this variant you need to use arrays of Integer as the sort method only takes a Comparator for arrays of objects. No worries about the calculations, auto-(un-)boxing will convert int to Integer and vice versa wherever necessary.

For variant 3 you just add code to reverse the whole result:

for (int i = 0; i &lt; n / 2; i++) {
    int temp = arr[i];
    arr[i] = arr[n - i - 1];
    arr[n - i - 1] = temp;
}

In general you should always use blocks ({}) to increase readability of your code, and the java style for declaring an array is int[] arr instead of int arr[] (although both styles work). This is because int[] is a class, while int is a primitive, and you see that better if the [] are next to the base type.

You would make your method twoWaySort more robust if you don't pass the length of the array as second parameter, but use arr.length inside the method.

huangapple
  • 本文由 发表于 2023年4月10日 23:16:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75978329.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定