Results 1 to 5 of 5
  1. #1
    MonkeyGrad is offline Member
    Join Date
    Apr 2011
    Posts
    2
    Rep Power
    0

    Default Checking if an ArrayList is sorted

    Hi all,

    I need a method which checks to see if an ArrayList is sorted in a ascending order. I keep getting an IndexOutofBound error. Wonder if you can help me to work around this.

    Java Code:
    public static boolean isSorted(ArrayList<Double> array) {
        boolean result = true;
        for(int i = 0; i <array.size(); i++) {
    
            if(array.get(i) >= array.get(i+1)) {
                result = false;
                break;
            }
        }
        return result;
    }

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    What happens when you get to the last element in the List? You still check to see if it is before the "next" element when there isn't one.

  3. #3
    MonkeyGrad is offline Member
    Join Date
    Apr 2011
    Posts
    2
    Rep Power
    0

    Default

    Quote Originally Posted by Junky View Post
    What happens when you get to the last element in the List? You still check to see if it is before the "next" element when there isn't one.
    I noticed that this was the problem but I am unsure of how to get around this.

  4. #4
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    Simple, stop looping too many times.

  5. #5
    Ruuhkis is offline Member
    Join Date
    Feb 2011
    Posts
    19
    Rep Power
    0

    Default

    This is what i made. It seems to work correctly. :) (it uses int array, not ArrayList. But its easy to change! :))
    public static boolean isSorted(int[] n){
    for(int x = 0; x < n.length-1; x++){
    if(n[x] > n[x+1])
    return false;
    }
    return true;
    }

Similar Threads

  1. Replies: 12
    Last Post: 11-26-2010, 09:33 AM
  2. Sorted Doubly linked List
    By student2889 in forum New To Java
    Replies: 1
    Last Post: 10-14-2010, 11:05 AM
  3. Casting an int from a sorted set
    By Bmack in forum New To Java
    Replies: 2
    Last Post: 03-17-2010, 08:09 PM
  4. Sorted LinkList problem
    By koolaqua16 in forum Advanced Java
    Replies: 1
    Last Post: 08-08-2009, 07:49 AM
  5. My doublyLinked list does not get sorted
    By hasani6leap in forum New To Java
    Replies: 0
    Last Post: 01-06-2008, 04:09 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •