1
1
123qwe2015-09-18 17:28:56
Algorithms
123qwe, 2015-09-18 17:28:56

How does bubbleSort know to start the loop over?

public class Bubble {
  public static void main(String args[]){
    int bubble[] = {2,1,7,5,6,8,3,1};
    int temp;
    boolean check = false;
    while(check == false){
      check = true;
    
      for(int i = 0;i < bubble.length-1;i++){
        
        if(bubble[i] > bubble[i+1]){
          temp = bubble[i+1];
          bubble[i+1] = bubble[i];
          bubble[i] = temp;
          check = false;
        }
      }
    }
    for(int i = 0; i < bubble.length;i++){
      System.out.println(bubble[i]);
    }
  }
}

I understand every line, except for the place in the for condition.
Why does it say length -1? I don't quite understand how it works, but I think the answer lies in this.
The loop goes through all the indexes and then it should return and start again, but I don't see that in the code.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vit, 2015-09-18
@Yonghwa

length-1 - because indexes start at zero, hence the last number is length-1.
"Start over" is the next iteration of the outer while loop. It will stop only when the condition in the if does not work inside the inner loop, i.e. when the array is sorted. Then check will become true and the next iteration of the while will not run.

L
LittleFatNinja, 2015-09-18
@LittleFatNinja

Why does it say length -1

because indexing starts from 0, respectively the index of the last element is "size-1"
for( int i = 0; i < bubble.length-1;i++)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question