int[] array = {1,1,0,1,2,2,0,0};
int firstNumber = 1;// dynamic can be 0 or 1 or 2
int numberOfOccurances = 0;
//Basic sort functionality
for(int i = 0 ; i< array.length; ++i)
{
if(array[i] == firstNumber)
{
numberOfOccurances++;
}
for(int j = i+1; j<array.length; ++j)
{
if(array[j] < array[i])
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
int[] requiredArray= new int[array.length];
for(int i = array.length-1 ; i >= 0; i--)
{
if(array[i] != firstNumber)
requiredArray[i] = array[i];
}
for(int i =0;i<array.length;i++)
{
if(i<numberOfOccurances)
requiredArray[i]= firstNumber;
}
//Print Output
for (int i = 0; i<requiredArray.length; i++)
System.out.print(requiredArray[i] + " ");
输出:1 1 1 1 0 0 2 2
我能够获得所需的输出,但我不确定这是否是解决我的问题的最佳方法?