IniziaInizia gratis

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.

Questo esercizio fa parte del corso

Optimizing Code in Java

Visualizza il corso

Istruzioni dell'esercizio

  • Iterate through all the numbers in numbers, using i as the iterator and starting at 0.
  • Iterate through all the numbers in numbers again, using j = i + 1, looping through numbers, and incrementing i.
  • Finish the return statement to return true when you have not found a pair in wrong order.

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

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 ____;
    }
}
Modifica ed esegui il codice