【问题标题】:Sorting of Array containing only 0,1 and 2排序仅包含 0,1 和 2 的数组
【发布时间】:2015-09-20 12:00:11
【问题描述】:

问题 - 给您一个仅包含 0 和 1 和 2 的数组。
编写一个函数对这个数组进行排序。

如果我输入2 2 2 1 1 1 0 0 0

输出即将到来0 2 2 2 2 2 2 2 2

请看下面写的代码

import java.util.Scanner;

public class SortZeroOneTwo {

    public static void sortZeroOneTwo(int[] input) {
        int i=0;
        int j=input.length-1;

        while(i<j) {
            if(input[i]==2) {
                for(int k=i+1;k<input.length;k++) {
                    input[k-1] = input[k];
                }
                input[j] = 2;
                j--;
            }
            i++;
        }
        i=0;
        j=input.length-1;

        while(i<j) {
            if(input[j]==0) {
                for(int k=i;k<j;k++) {
                    input[k+1] = input[k];
                }
                input[i]=0;
                i++;
            }
            j--;
        }

    }

    public static void printArray(int[] input) {
        System.out.println("The required sorted array is : ");
        for(int i=0;i<input.length;i++) {
            System.out.print(input[i] + " ");
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("Enter the length of the array");
        Scanner s = new Scanner(System.in);

        int n = s.nextInt();

        int[] array = new int[n];
        for(int i=0;i<array.length;i++) {
            System.out.println("Enter the next array element");
            array[i] = s.nextInt();
        }

        sortZeroOneTwo(array);
        printArray(array);

    }

} 

【问题讨论】:

  • 嗯,有什么问题,有什么问题吗?
  • 您所要做的就是计算有多少 01 ;)

标签: java arrays sorting


【解决方案1】:

试试这个:

private static final int MAX = 2;
public static void sortZeroOneTwo(int[] input) {
    int []values = new int[MAX+1];
    for (int element: input) {
        values[element]++;
    }
    int j = 0;
    for (int i = 0 ; i < values.length; i++){
        for (int k = 0; k < values[i]; k++){
            input[j++] = i;
        }
    }
}

public static void main(String[] args) {
    int[] input = {2,2,2,1,1,1,0,0,0};
    sortZeroOneTwo(input);
    for (int element : input) {
        System.out.print(element+" ");
    }
    System.out.println();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多