-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);
}
}
Ну, в чем проблема, есть ли проблема вообще? –
Все, что вам нужно сделать, это подсчитать, сколько существует '0' и' 1';) – alfasin