有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java对0、1和2的数组进行排序

我正在尝试以这样一种方式对数组进行排序:所有的零都应该先出现,然后是1,然后是2

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]

共 (3) 个答案

  1. # 1 楼答案

    从fast look来看,您似乎只需要使用i <= high

    while (i <= high) 
    
  2. # 2 楼答案

    high的数字还没有检查

        while (i <= high) {
    
  3. # 3 楼答案

    或者可以使用计数排序:使用三个计数器对数组进行单次扫描。然后把#0#1#2写回数组

    计数排序在以下情况下工作:

    • 可能的域值是已知的,基数很小
    • 允许少量额外存储(等于基数)

    计数排序是O(n)-比任何比较排序都快