gpt4 book ai didi

java - 对零、一和二的数组进行排序

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:44:47 24 4
gpt4 key购买 nike

我正在尝试以这样一种方式对数组进行排序,即所有零都应该排在第一位,然后是一个,然后是两个。

Input: { 0, 1, 2, 1, 2, 2, 0, 0, 1 };

Output: { 0, 0, 0, 1, 1, 1, 2, 2, 2 };

下面是我的程序,它对我上面的输入不起作用:

public class SeggregateZeroOneTwos {

public static void main(String[] args) {
int[] a = { 0, 1, 2, 1, 2, 2, 0, 0, 1 };
arrangeNumbers(a);
System.out.println(Arrays.toString(a));
}

public static void arrangeNumbers(int[] arr) {
int low = 0;
int high = arr.length - 1;
int i = 0;
while (i < high) {
if (arr[i] < 1) {
swap(arr, i, low);
low++;
i++;
} else if (arr[i] > 1) {
swap(arr, i, high);
high--;
} else {
i++;
}
}
}

public static void swap(int[] arr, int i, int j) {
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
}

我得到的输出如您所见,0 出现在 1 和 2 之间。代码有什么问题?

[0, 0, 1, 1, 1, 0, 2, 2, 2]

最佳答案

high 的数字还没有检查。

    while (i <= high) {

关于java - 对零、一和二的数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30564213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com