HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaMinor

Sort array of Numbers with some values always first

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arraywithnumbersalwaysfirstsomevaluessort

Problem

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= 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] + "  ");


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.

Solution

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

Code Snippets

public static void sortFirst(int first, int[] array) {
    int left = 0;
    for (int right = 0; right < 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);
}

Context

StackExchange Code Review Q#107658, answer score: 6

Revisions (0)

No revisions yet.