Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determines if the array list is sorted

I need to estimate if the array list is sorted (don't sort).

When Strings are sorted, they are in alphabetical order. I try to use compareTo() method to determine which string comes first

And return true if the array list is sorted, else false.

Code:

public boolean isSorted()
{
    boolean sorted = true;        
    for (int i = 1; i < list.size(); i++) {
        if (list.get(i-1).compareTo(list.get(i)) != 1) sorted = false;
    }

    return sorted;
}

Easy test:

    ArrayList<String> animals = new ArrayList<String>();
    ArrayListMethods zoo = new ArrayListMethods(animals); 
    animals.add("ape");
    animals.add("dog");
    animals.add("zebra");

    //test isSorted
    System.out.println(zoo.isSorted());
    System.out.println("Expected: true");

    animals.add("cat");
    System.out.println(zoo.isSorted());
    System.out.println("Expected: false");

    animals.remove("cat");
    animals.add(0,"cat");
    System.out.println(zoo.isSorted());
    System.out.println("Expected: false");

    **Output:**
    false
    Expected: true
    false
    Expected: false
    false
    Expected: false

This easy test shows only 1/3 coverage.

How to solve this issue.

like image 813
catch23 Avatar asked Jul 06 '13 06:07

catch23


1 Answers

You have a small bug in your method. Should be :

public boolean isSorted()
{
    boolean sorted = true;        
    for (int i = 1; i < list.size(); i++) {
        if (list.get(i-1).compareTo(list.get(i)) > 0) sorted = false;
    }

    return sorted;
}

>0 instead of !=1, you can't be sure that 1 is returned..

like image 123
Grisha Weintraub Avatar answered Nov 05 '22 16:11

Grisha Weintraub