Search code examples
javaarrayssortingmin

Generate an output from a sorted ascending array based on index


I want to generate an output using 2 different sets of arrays.

    int[] A = {7, 3, 8, 21, 5, 11};
    int[] B = {3, 5, 1};

Using a method, I want to sort array A but not array B to produce an output with the B[i]th value of the smallest number in array A.

For example, B[3] would equal to the 3rd smallest element of A which is 7.

Afterwards, I want to sort the output in ascending order, but I've figured that part out. I'm only having issues getting the right values from A.

This is what I've come up with so far:

public static void Algorithm2(int[] A, int[] B) {
    sortOrder(A);
    
    int[] result = new int[B.length];
    int min = A[0];
    
    for(int i = 0; i < A.length; i++) {
        if(B[i] >= min) {
            result[i] = A[B[i] -1];
        }
    }
    
    sortOrder(result);
    System.out.println(Arrays.toString(result));
    
    /*
    A is [3, 5, 7, 8, 11, 21]
    B is [3, 5, 1]
    Desired output is [3, 7, 11] 
     */
}

So far, this is what I've come up with but I can't seem to figure out how to the correct values from A.

Thanks in advance.


Solution

  • I think this is what you want.

    • first, sort A as stated.
    • then stream the values of B and, subtracting one, index into the sorted version of A.
    • Then sort the result.
    Arrays.sort(A);
    int[] result = Arrays.stream(B).map(i->A[i-1]).sorted().toArray();
    System.out.println(Arrays.toString(result));
    

    Prints

    [3, 7, 11]