仅包含0,1和2的数组排序 [英] Sorting of Array containing only 0,1 and 2

查看:78
本文介绍了仅包含0,1和2的数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Question - You are given with an array containing only 0’s and 1’s and 2's.
Write a function to sort this array.

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

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

请参阅到目前为止编写的以下代码

Please see the below code written so far

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);

    }

} 

推荐答案

尝试一下:

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();
}

这篇关于仅包含0,1和2的数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆