I have a homework assignment where I am asked to:
Write a method
sort(int[] arr)that takes an integer array and uses a method from a previous exercise to determine if the array is sorted in increasing order or not. If it is already sorted, it should return the array, if it is not, the method should sort the array before returning it.
My problem is that I don't know how I should approach this assignment? Should I modify the previous method, call it within a new method or can I create a method within the method? This is the previous method that I wrote:
public static void isSorted(int[] checkArray) {
boolean isSorted = true;
for (int i = 1; i < checkArray.length; i++) {
if (checkArray[i - 1] > checkArray[i]) {
isSorted = false;
Thanx in advance
In the interest of you actually learning something, here's my solution:
public int[] sort(int[] arr) {
if (!isSorted(arr))
Arrays.sort(arr);
return arr;
}
Here is the documentation for Arrays.sort
Not only is this more concise, it also does the sort in-place. This means that instead of copying the array you pass in, doing the work, and then returning the copy, it just does the work on the original array. This makes it slightly faster and means it takes up a minimal amount of extra space. Not that big a deal when your input size is 10, but it is when you get to 10 million. Also, note the wording of the assignment: If it is already sorted, it should return the array, if it is not, the method should sort the array before returning it. Technically, returning a copy of the original array is not what the assignment wants. It wants the original.
So it's short, clean, fast, and memory efficient. It must be good, right?
No, because it has one huge flaw. It breaks the implied contract of the method. A function that changes its arguments should not return anything, and a function that returns something should not modify its arguments. This is a basic principle of software engineering (and one that Arrays.sort demonstrates). Violating this can cause huge problems for those who assume you're competent and won't break this rule.
If we follow the rule, sort should be this:
public void sort(int[] arr) {
if (!isSorted(arr))
Arrays.sort(arr);
}
So tell your teacher an armored hamster you met on the Internet said to stop teaching you poor interface design.
I read "uses [the] method" to mean "calls the method". That said, testing for sortedness before sorting seems somewhat pointless, so it might be worth double-checking with whoever gave you that assignment.
One issue with your previous method is that it doesn't return anything. You'll need to do something about that to make it useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With