Ok, let's go through this together. Follow me:
The question ask to create a method
that takes an array of integers as an
argumetn and returns a sorted set
containing the elements of the that
array.
We have three steps here:
- we need to figure out how to pass an array to a function
- we need to figure out how to sort elements
- we need to figure out how to return an array (of sorted elements)
What I'm doing here is taking the main problem and dividing it into smaller, more approachable sub-problems. It's called divide et impera. You'll encounter this approach very often if you pursue a programming career.
- pass an array to a function: write a simple program that prepares an array, passes it to a function and have the function print it. Something like (in my own just-made up version of a pseudocode):
main() {
a[] = { "one", "two", "three"};
f(a);
}
f(arr[]) {
for ( int i = 0 ; i < arr.length ; i++ )
print(arr[i]);
}
You with me so far? I hope so.
Now,
- sorting of elements: I'm pretty sure you already have a way of doing it in your textbook or your notes. Remember you must sort an array. Now our function
f()
would look something like:
f(arr[]) {
/* insert here your sorting method */
}
Once this is done, you need to pass back this array to the main function. Now, if you were to pass back a single value from a function, you would do something like:
int g() {
int i = 0;
i++;
return i;
}
since they want you to return an array, it would be something like:
int[] h() {
/* initialize the array */
int[] j = { 1, 2, 3 };
/* your code goes here */
return j;
}
At this point you have all elements you need for the question you were asked. Just make them work in java first, then put everything together.
Welcome to the magic world of programming :)