CommencerCommencer gratuitement

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.

Cet exercice fait partie du cours

Optimizing Code in Java

Afficher le cours

Instructions

  • 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.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de 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 ____;
    }
}
Modifier et exécuter le code