0

I am new to Java, so please accept my apology. I have an ordered array-list i.e. { 10, 10, 10, 10, 120, 120 }.

How can I loop through the list to check the int 10 are placed at the top of the list and int 120 are placed at the bottom of the list?

I tried using

for(int i=0; i<list.size(); i++){
  for(int j=0; j<list.size(); j++){

  }
}

but that's how far I could get / understand.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
Joe
  • 9
  • 2
  • 3
    You say you have an **ordered** i.e. **sorted** array. Now you want to check whether the array is **sorted** correctly? Well, of course it is, it was sorted before already. Or do you want to check whether an **unknown** array is sorted? – Zabuzard Oct 20 '17 at 21:17
  • Also, your for loops look like you're trying to iterate over a 2D ArrayList, but your description only describes a 1D ArrayList – Taelsin Oct 20 '17 at 21:19
  • 2
    Possible duplicate of [How to determine if a List is sorted in Java?](https://stackoverflow.com/questions/3047051/how-to-determine-if-a-list-is-sorted-in-java) – Zabuzard Oct 20 '17 at 21:23

3 Answers3

2

First of all, you're using two nested for loops. This is not necessary in your case, it's sufficient to use a single for loop. Furthermore, I recommend you to not focus your test on specific values. Try to think in a more high level way. In this case you should test that every item in the list is greater than the previous one. So you should start from the second element (index 1) and go throughout the array, comparing each item with the previous one.

for (int i = 1; i < list.size(); i++) {
    if (list.get(i) < list.get(i - 1)) {
        System.out.println("list not properly ordered");
        return;
    }
}

System.out.println("list correctly ordered");
return;
sirnino
  • 437
  • 3
  • 13
  • This is a good answer (+1) for accessing an array-based list, like the list in the question. It will however not perform well for non-array lists, such as `LinkedList`. For good performance on all types of lists, an `Iterator` should be used, e.g. using an enhanced `for` loop, as shown in [this answer](https://stackoverflow.com/a/46857633/5221149). – Andreas Oct 20 '17 at 21:35
0

Well, if you want to check if the list is sorted, you could compare adjacent elements to see if the list is always staying the same or increasing - something in the middle like

if (list.get(i) > list.get(i + 1)) {
    return false;
}
0

Here is an alternative to the answer by @sirnino, using the enhanced for loop.

The advantage is that it'll perform good, even on lists that are not array-based, such as LinkedList, since it uses the Iterator, not get(index).

int prev = Integer.MIN_VALUE;
for (int value : list) {
    if (prev > value) {
        System.out.println("list not properly ordered");
        return;
    }
    prev = value;
}
System.out.println("list correctly ordered");
return;
Andreas
  • 154,647
  • 11
  • 152
  • 247