Sort array of Numbers with some values always first The first number will be dynamically selected and remaining array should be sorted ascending

    int[] array = {1,1,0,1,2,2,0,0};
    int  firstNumber = 0;// dynamic can be 0 or 1 or 2
    int numberOfOccurances = 0;

    //Basic sort functionality
    for(int i = 0 ; i&lt; array.length; ++i)
    {
        if(array[i] == firstNumber)
        {
            numberOfOccurances++;
        }
        for(int j = i+1; j&lt;array.length; ++j)
        {   
            if(array[j] &lt; 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 &gt;= 0; i--)
    {
        if(array[i] != firstNumber)
        requiredArray[i] = array[i];

    }
    for(int i =0;i&lt;array.length;i++)
    {
        if(i&lt;numberOfOccurances)
        requiredArray[i]= firstNumber;
    }

    //Print Output
    for (int i = 0; i&lt;requiredArray.length; i++)
    System.out.print(requiredArray[i] + "  ");


Output:


1 1 1 1 0 0 2 2



I was able to get desired output. But not sure if this is the best way to solve in terms of speed.
This can be easily done using a two-phase approach, one to shift values to the front that you want to keep, the other to sort the remainder.

Note, for sorting, use the native functions in the libraries... in this case, Arrays.sort(...)

It would also be much better to wrap this up in a function, taking 2 arguments, the number to put first, and the array to sort.

public static void sortFirst(int first, int[] array) {
    int left = 0;
    for (int right = 0; right &lt; array.length; right++) {
        if (array[right] == first) {
            // swap left and right... put the first values first.
            array[right] = array[left];
            array[left] = first;
            left++;
        }
    }

    // OK, now we have "left" pointing to the actual data that needs sorting
    Arrays.sort(array, left, array.length);
}