ComeçarComece de graça

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.

Este exercício faz parte do curso

Optimizing Code in Java

Ver curso

Instruções do exercício

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

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

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 ____;
    }
}
Editar e executar o código