Bill
Bill

Reputation: 145

Out of bounds error in a loop

public static void bubbleSort(Farm a[], int n) {
String[] animals = getString(a);

for(int i = 0; i < n - 1; i++)  {

  boolean swapped = false;
  for(int j = 0; j < n - 1 - i; j++) {

    int c = animals[j].compareTo(animals[j+1]);
    if(c > 0) {
      swap(animals, j, j+1);
      swapped = true;
    }
  }
  if(!swapped) 
    break;
}
for (int i = 0; i < a.length; i++)
  if(a[i] != null)
  System.out.println(a[i].animal);

}

in int c = animals[j].compareTo(animals[j+1]); it is giving me an out of bounds error for some reason

Upvotes: 0

Views: 130

Answers (1)

Upul Bandara
Upul Bandara

Reputation: 5958

It seems like n >= animals.length

Check boundary values in the for loops again

Upvotes: 1

Related Questions