Implementing a sort checker application
You're implementing a method to check if an ArrayList
of integers is sorted in ascending order. The current implementation compares every possible pair of elements in the list to ensure they are in the correct order.
This exercise is part of the course
Optimizing Code in Java
Exercise instructions
- Iterate through all the numbers in
numbers
, usingi
as the iterator and starting at0
. - Iterate through all the numbers in
numbers
again, usingj = i + 1
, looping throughnumbers
, and incrementingi
. - Finish the return statement to return
true
when you have not found a pair in wrong order.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
int arraySize = 1000;
ArrayList unsortedNumbers = new ArrayList<>();
for (int i = 0; i < arraySize; i++) {
unsortedNumbers.add(i);
}
int temp = unsortedNumbers.get(arraySize - 1);
unsortedNumbers.set(arraySize - 1, unsortedNumbers.get(arraySize - 2));
unsortedNumbers.set(arraySize - 2, temp);
SortChecker checker = new SortChecker();
boolean result = checker.isSorted(unsortedNumbers);
System.out.println("Unsorted array result: " + result);
}
}
class SortChecker {
public boolean isSorted(ArrayList numbers) {
// Iterate through all the numbers
for (____) {
// Iterate through all the numbers again
for (____) {
if (numbers.get(i) > numbers.get(j)) {
return false;
}
}
}
// Return if we have not returned false so far
return ____;
}
}