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.
Diese Übung ist Teil des Kurses
Optimizing Code in Java
Anleitung zur Übung
- Iterate through all the numbers in
numbers, usingias the iterator and starting at0. - Iterate through all the numbers in
numbersagain, usingj = i + 1, looping throughnumbers, and incrementingi. - Finish the return statement to return
truewhen you have not found a pair in wrong order.
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
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 (int i = ____; i < numbers.size(); ____) {
// Iterate through all the numbers again
for (int j = ____; j < numbers.size(); ____) {
if (numbers.get(i) > numbers.get(j)) {
return false;
}
}
}
// Return if we have not returned false so far
return ____;
}
}