2015-07-02 4 views
-2

Вопрос: вам предоставляется массив, содержащий только 0 и 1 и 2.
Напишите функцию для сортировки этого массива.Сортировка массива, содержащего только 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); 

    } 

} 
+1

Ну, в чем проблема, есть ли проблема вообще? –

+5

Все, что вам нужно сделать, это подсчитать, сколько существует '0' и' 1';) – alfasin

ответ

0

Попробуйте с этим:

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