I'm having trouble creating an output based on 2 different arrays. For example, I have 2 arrays "A" and "B". I sorted the elements in ascending order using this method:
public static void sortOrder(int [] A) {
for(int i = 0; i < A.length; i++) {
for(int k = i + 1; k < A.length; k++) {
if(A[i] > A[k]) {
int temp = A[i];
A[i] = A[k];
A[k] = temp;
}
}
}
}
I want to output the B[i]th smallest number in array A.
For example, after sorting, array A = [3, 5, 7, 8, 11, 21] and B is [1, 3, 5].
The desired output is [3, 7, 11] as the 1st smallest element of A is 3, the 3rd smallest element of A is 7, and the 5th smallest element of A is 11.
So far this is what I came up with:
public static void Algorithm1(int [] A, int [] B) {
sortOrder(A);
sortOrder(B);
int[] result = new int[B.length];
int min = A[0];
for(int i = 0; i < A.length; i++) {
for(int k = 0; k < B.length; k++) {
if(B[k] <= min) {
result[k] = A[k];
}
}
}
System.out.println(Arrays.toString(result));
//A is [3, 5, 7, 8, 11, 21]
//B is [1, 3, 5]
//Desired output is [3, 7, 11]
}
Running this code I get an output of [3, 5, 0]. I know the problem probably lies with the nested for loop but for the life of me I cannot figure out how to solve it. Sorry if I didn't explain what I want clearly enough as I am still quite new to programming.
Thanks in advance!!
You do not need to have a nested loop and go through both arrays, you simply need to loop through the result.length
or B.length
(as they are always equal) and take the value of B[i] - 1
and use it as the index to access A
. This leaves you with result[i] = A[B[i] - 1];
.
Fixed Code:
public static void Algorithm1(int [] A, int [] B) {
sortOrder(A);
sortOrder(B);
int[] result = new int[B.length];
for(int i = 0; i < result.length; i++) {
result[i] = A[B[i] - 1];
}
System.out.println(Arrays.toString(result));
}
Test Run:
public static void main(String args[]) throws Exception {
int [] arr1 = new int[]{21, 8, 11, 7, 5, 3};
int [] arr2 = new int[]{3, 5, 1};
Algorithm1(arr1, arr2);
}
Output:
[3, 7, 11]