1 | int[] numbers = { 5, 8, 14, 1, 5678 };
2 | int tempVar;
3 | for (int i = 0; i < numbers.length; i++)
4 | {
5 | for(int j = 0; j < numbers.length; j++)
6 | {
7 | if(numbers[i] > numbers[j + 1])
8 | {
9 | tempVar = numbers [j + 1];
10 | numbers [j + 1]= numbers [i];
11 | numbers [i] = tempVar;
12 | }
13 | }
14 | }
15 | for (int i = 0; i < numbers.length; i++)
16 | {
17 | System.out.println(numbers[i].toString());
18 | }
I am a newbie to Java who learn on my own. I have some problems with bubble sorting.
My problems are with line 5 to 7. From my understanding, the outer
loop starts with i is 0, then the inner loop runs from j is 0 and
increases by 1 each time until j reaches 4, after which the outer loop
will advance to i is 1. Thus before the outer loop advances to i is
1, the following should happen.
When i=0, number i=5 Then the inner loop runs:
When j=0, number j=5
When j=1, number j=8
When j=2, number j=14
When j=3, number j=1
When j=4,number j=5678
Then if numbers i is greater than numbers j+1, the two numbers are
swapped.
Then we are comparing 5 with 5, then 5 with 8, then 5 with 14, then 5
with 1, and then 5 with 5678, which is different from how bubble sort
works (which compares 5 with 8, then 8 with 14, then 14 with 1 and
then 1 with 5678).
I can’t understand how the codes in line 5 to 7 can result in
comparing the two neighboring figures in the way supposed to be in
bubble sort. Can anyone point out what I have thought wrong?
It would be grateful if any one points out, in greater detail, how
lines 5 to 7 work. It would be even better if a step by step
breakdown could be provided. Thanks!